2016-03-08 45 views
1

可变比较类名我有类的名字,如在JavaScript

<input class="so os us"> 

输入元素就是我想要做的是一个变量是否匹配特定的类名,然后做一些事情

$(function(){ 
    var x="os"; 
    var y=$("input").attr("class"); 
    if(x=y){ 
    //since the class name contains the word "os" it has to perform the actions mentioned here 
    } 
}); 

我不知道如何实现这一点。

+0

打印变量'y'在屏幕上,使用'alert'左右。然后你会看到为什么'x'不匹配'y'。 – Peter

回答

3

您可以使用.hasClass()

$(function() { 
 
    var x = "os"; 
 
    var y = $("input").hasClass(x); 
 
    if (y) { 
 
    $('input').val('foobar!!!').css('color', 'red'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class="so os us">

+0

谢谢兄弟我正在尝试搜索,但这很容易 –

+0

不客气@SugumarVenkatesan – Jai