如果某些元素在 Wordpress Widget 中包含某个类,我会尝试查找这些元素。但我不明白的是为什么 authors.hasClass()
没问题,但 currentAuthor.hasClass()
抛出错误,说它不是函数!
HTML
<ul>
<li class="active"></li>
<li></li>
</ul>
JS
var authors = jQuery("li");
authors.hasClass("active");
for (i = 0; i < authors.length; i++) {
var currentAuthor = authors[i];
currentAuthor.hasClass("active");
}
最佳答案
通过将对象作为数组循环,您将它们视为标准的 JavaScript 对象。因为 hasClass()
是一个 jQuery 方法,所以它只能用在 jQuery 对象上。您可以改用 jQuery 的 .each()
,其中 jQuery(this)
指的是循环中的当前元素。
var authors = jQuery("li");
authors.each(function() {
if (jQuery(this).hasClass("active")){
//Do stuff
}
});
话虽这么说,为什么选择所有 li
元素然后检查它们是否具有事件类,而您可以简单地选择所有事件元素?
var $active = jQuery("li.active");
$active.each(function() {
//Do stuff
});
或者根据你正在做的事情,你甚至可能不需要 each()
// Turn all active li elements red
var $active = jQuery("li.active");
$active.css("color", "red");
关于javascript - jQuery hasClass 无法循环遍历子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737610/