首页 > 解决方案 > jQuery .hasClass() 在 each() 上的 children() 不工作“不是一个函数”

问题描述

我试图遍历一个 div 的孩子并找出哪个有这个is-active类:

$('.childrenContainerSelector').children().each(child => console.log(child.hasClass('is-active'));

但是当我运行代码时,我得到了hasClass() is not a function错误。

如果我只运行:

$('.childrenContainerSelector').children() 

作为输出,我确实得到了正确的孩子。

标签: jquery

解决方案


检查文档.each()

回调函数的参数是(Integer index, Element element)你试图调用hasClass()一个int.

请注意,第二个参数是 anElement而不是jQuery这样,如果您想使用 jQuery 方法,则需要将其包装起来

$('.childrenContainerSelector').children().each((i, child) => 
  console.log($(child).hasClass('is-active'))

或者,使用内置classList方法

child.classList.contains("is-active")

如果您只是在跟班的孩子之后is-active,为什么不使用

const activeChildren = $(".childrenContainerSelector > .is-active")

推荐阅读