jquery - jQuery .hasClass() 在 each() 上的 children() 不工作“不是一个函数”
问题描述
我试图遍历一个 div 的孩子并找出哪个有这个is-active
类:
$('.childrenContainerSelector').children().each(child => console.log(child.hasClass('is-active'));
但是当我运行代码时,我得到了hasClass() is not a function
错误。
如果我只运行:
$('.childrenContainerSelector').children()
作为输出,我确实得到了正确的孩子。
解决方案
检查文档.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")
推荐阅读
- javascript - 如何将 json 文件导入 index.html(将标记放入地图)
- asp.net - URL 图像未显示在 View Razor ASP.NET CORE 3.1 中
- python - 如何发出 API 请求?
- c# - 继承层次结构中的虚拟键、覆盖键和新键
- css - 在其父级的 100% 高度创建一个 div
- jquery - Laravel 页面速度分析
- python - NotFound:404 未找到(错误代码:10011):未知角色
- javascript - 使用 Grunt 任务运行器时未找到任务错误
- javascript - 使用自定义数据和布局属性以编程方式创建图标
- react-native - ReactNative 问题与构造函数说';' 错误