Javascript jQuery 检查 Attr 类是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6859297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery check if Attr Class exists?
提问by Tom
How do I determine if the .attr('class')
exists?
我如何确定是否.attr('class')
存在?
I am using this code:
我正在使用此代码:
if(jQuery(this).attr('class') != undefined && jQuery(this).hasClass('myclass')) {
//Do something
}
It doesn't seem to work.
它似乎不起作用。
回答by Abraham
It depends on what you want. Do you want to check if an element has the class attribute, such as:
这取决于你想要什么。是否要检查元素是否具有 class 属性,例如:
<div class></div>
<div class=""></div>
<div class="abc"></div>
If so, use:
如果是这样,请使用:
if ($('div').attr('class') != undefined)...
If you're trying to check if the element has a specific class, use:
如果您尝试检查元素是否具有特定类,请使用:
if ($('div').hasClass('abc'))...
回答by Manikandan Thangaraj
Try this..
尝试这个..
if(jQuery('#id1').attr('class') =="") { alert($('#id1').attr('class')); }
<div id="id1">test</div>
if(jQuery('#id1').attr('class') =="") { alert($('#id1').attr('class')); }
<div id="id1">test</div>
回答by mdskinner
You can check if an element with any class exists by just calling 'length' on a jquery object.
您可以通过在 jquery 对象上调用 'length' 来检查是否存在具有任何类的元素。
$('.myclass').length
回答by Reporter
The return value if the attribute class doesn't exists is null or an empty string.
如果属性类不存在,则返回值为 null 或空字符串。
回答by Joseph Marikle
this code works actually: fiddle
这段代码实际上有效:fiddle
HTML:
HTML:
<div></div>
<div class="myclass"></div>
<div class="blah"></div>
<div></div>
<div class="myclass"></div>
<div class="myclass"></div>
<div></div>
<div class="myclass andAnotherClass"></div>?
JS:
JS:
$("div").each(function(){
if(jQuery(this).attr('class') != undefined && jQuery(this).hasClass('myclass')) {
jQuery(this).html("I have it");
} else {
jQuery(this).html("I don't have it");
}
});?