简体   繁体   English

jQuery hasClass无法遍历子级

[英]jQuery hasClass doesn't work looping through children

I'm trying to look for certain elements if they contain a certain class in a Wordpress Widget. 我正在尝试寻找某些元素,如果它们在Wordpress窗口小部件中包含某个类。 But what I can't understand is why the authors.hasClass() is OK, but the currentAuthor.hasClass() throws an error saying it's not a function! 但是我不明白的是为什么authors.hasClass()可以,但是currentAuthor.hasClass()抛出一个错误,说它不是函数!

HTML HTML

<ul>
    <li class="active"></li>
    <li></li>
</ul>

JS JS

var authors = jQuery("li");
authors.hasClass("active");

for (i = 0; i < authors.length; i++) { 
    var currentAuthor = authors[i];
    currentAuthor.hasClass("active");
}

By looping through the objects as an array, youre looking at them as standard JavaScript objects. 通过将对象作为数组循环,您可以将它们视为标准JavaScript对象。 Because hasClass() is a jQuery method, it can only be used on jQuery objects. 由于hasClass()是jQuery方法,因此只能在jQuery对象上使用。 You can use jQuery's .each() instead, where jQuery(this) refers to the current element in the loop. 您可以改用jQuery的.each() ,其中jQuery(this)引用循环中的当前元素。

var authors = jQuery("li");

authors.each(function() {
    if (jQuery(this).hasClass("active")){
        //Do stuff
    }
});

That being said, why select all the li elements and then check if they have the active class, when you can simply just select all active elements? 话虽如此,为什么您只需选择所有活动元素,然后为什么选择所有li元素然后检查它们是否具有活动类呢?

var $active = jQuery("li.active");

$active.each(function() {
    //Do stuff
});

Or depending on what you're doing, you may not even need each() 或者根据您的工作,甚至可能不需要each()

// Turn all active li elements red
var $active = jQuery("li.active");
$active.css("color", "red");

Beacuse authors[i] returns not jQuery object but raw DOM element (so it doesn't have jQuery methods like hasClass ). 因为authors[i]不返回jQuery对象,而是返回原始DOM元素(因此它不具有hasClass类的jQuery方法)。 According to jQuery docs: 根据jQuery文档:

A jQuery object is an array-like wrapper around one or more DOM elements. jQuery对象是围绕一个或多个DOM元素的类似数组的包装。 To get a reference to the actual DOM elements (instead of the jQuery object), you have two options. 要获得对实际DOM元素(而不是jQuery对象)的引用,您有两个选择。 The first (and fastest) method is to use array notation... 第一种(也是最快的)方法是使用数组符号...

To solve your problem you have to wrap returned element in jQuery object like this: 为了解决您的问题,您必须将返回的元素包装在jQuery对象中,如下所示:

var currentAuthor = $(authors[i]);

or use eq method to get jQuery object from collection: 或使用eq方法从集合中获取jQuery对象:

var currentAuthor = authors.eq(i);

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

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