简体   繁体   English

jQuery hasClass对我不起作用?

[英]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拥有它。

Updated Fiddle 更新小提琴

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>

You have to select div not span , as div has class of 'adding' 您必须选择div not span,因为div具有“ adding”类

alert($('div').hasClass('adding'));

Demo 演示版

如果要检查任何span的孩子都上过课,则可以这样尝试;

alert($('span').children().hasClass('adding'));

范围内的div不是一个好习惯,并且您的范围内没有任何添加的类,添加是其子对象的类,因此请使用

alert($('span').children().hasClass('adding'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM