jQuery addClass到每个具有’.class’子元素的元素

我正在尝试为#somecontainer中的每个锚添加一个Class,其子项有.someclass

例如.

<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass">/span></a>
</div>

在上面的代码中,我希望第一个和第三个锚具有类’.anotherclass’
我试过这个代码,但似乎没有用

jQuery('#container a').each(function(){
jQuery(this).has('.someclass').addClass('anotherclass');
})

Update: .has() returns a boolean and not jQuery object. That’s why the
code didn’t work

解决方法

我怀疑你的问题源于你的HTML格式错误,即你需要关闭你的跨度.
<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass"></span></a>
</div>

此外,您可以通过以下方式简化代码:必须仅选择包含与所需类名匹配的元素的锚:

$('#container a:has(.someclass)').addClass('anotherclass');

即“选择所有锚点作为具有ID容器的元素的后代,并且具有类someclass的后代”

正如Jon所指出的,另一种方法是使用基本选择器,然后使用自定义函数过滤生成的集合:

$('#container a').filter(function(){
    return $(this).has('.someclass').length > 0
}).each(function(){
    $(this).addClass('anotherclass');
});

对于要保留的任何元素,该函数需要返回true,对于您不保留的任何元素,该函数需要返回false.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...