rzr*_*rzr 7 each jquery addclass
我想添加一个类里面每个锚#somecontainer,其子女有.someclass
例如.
<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass">/span></a>
</div>
Run Code Online (Sandbox Code Playgroud)
在上面的代码中我希望第一个和第三个锚点有一个类'.anotherclass'我尝试了这个代码,但它似乎不起作用
jQuery('#container a').each(function(){
jQuery(this).has('.someclass').addClass('anotherclass');
})
Run Code Online (Sandbox Code Playgroud)
更新:
.has()返回一个boolean而不是jQuery对象.这就是代码不起作用的原因
Asa*_*din 12
我怀疑你的问题源于你的HTML格式错误,即你需要关闭你的跨度.
<div id="container">
<a><span class="someclass"></span></a>
<a></a>
<a><span class="someclass"></span></a>
</div>
Run Code Online (Sandbox Code Playgroud)
此外,通过使用:has仅包含与所需类名匹配的元素的锚点,可以简化您的代码:
$('#container a:has(.someclass)').addClass('anotherclass');
Run Code Online (Sandbox Code Playgroud)
即"选择所有锚点,这些锚点是具有ID container且具有类的后代的元素的后代someclass"
正如Jon所指出的,另一种方法是使用基本选择器,然后使用自定义函数过滤生成的集合:
$('#container a').filter(function(){
return $(this).has('.someclass').length > 0
}).each(function(){
$(this).addClass('anotherclass');
});
Run Code Online (Sandbox Code Playgroud)
该函数需要返回true您要保留false的任何元素,以及您不想要的任何元素.
| 归档时间: |
|
| 查看次数: |
28696 次 |
| 最近记录: |