[英]jQuery hasClass doesn't work for me?
In following code, hasClass
doesn't work and result is false
in alert. 在以下代码中,
hasClass
不起作用,并且警报结果为false
。 why, what do i do? 为什么,我该怎么办?
Online Demo: http://jsfiddle.net/Fe3CK/ 在线演示: http : //jsfiddle.net/Fe3CK/
HTML: HTML:
<span>
<div class="adding"></div>
</span>
JS: JS:
alert($('span').hasClass('adding'));
I think you might be misunderstanding what .hasClass
does. 我认为您可能会误解
.hasClass
功能。 It checks whether the element itself has one of these classes assigned. 它检查元素本身是否分配了这些类之一。 From the documentation :
从文档中 :
Determine whether any of the matched elements are assigned the given class.
确定是否为任何匹配的元素分配了给定的类。
If you want to check whether the element contains an element with that class, use .has
: 如果要检查元素是否包含该类的元素,请使用
.has
:
Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
将匹配的元素集减少为后代与选择器或DOM元素匹配的元素。
alert($('span').has('.adding').length > 0);
You need: 你需要:
alert($('span div').hasClass('adding'));
since your span
does not have any class adding
. 因为您的
span
没有adding
任何类。 Only the child div of your span has it. 只有您跨度的子div拥有它。
Note: Only inline elements may be contained within inline elements. 注意:内联元素中只能包含内联元素。 span is an inline element so block level elements like div or p cannot appear within a span.
span是内联元素,因此div或p之类的块级元素不能出现在span内。
Hence, <div>
inside <span>
tag is not a valid HTML5 markup so you should use <div>
instead of <span>
in this case. 因此,
<div>
<span>
标记内的<div>
不是有效的HTML5标记,因此在这种情况下,应使用<div>
而不是<span>
。
如果要检查任何span的孩子都上过课,则可以这样尝试;
alert($('span').children().hasClass('adding'));
范围内的div不是一个好习惯,并且您的范围内没有任何添加的类,添加是其子对象的类,因此请使用
alert($('span').children().hasClass('adding'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.