如何使用jQuery过滤不需要的元素 [英] How to filter undesired elements with jQuery
本文介绍了如何使用jQuery过滤不需要的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以使用两个div,
<div class="main right"></div>
<div class="main"></div>
和这个jQuery代码片段,如下:
And this jQuery snippet, as it follows:
$('.main').css('background-color','red');
这会将div背景颜色都改为红色,正常。我想知道如何改变只有main作为类,而不是main right的div的颜色。
This will change both divs background-color to red, as normal. I'd like to know how to change that color for the divs that have only "main" as class, not "main right",
推荐答案
$('.main:not(.right)').css('background-color','red');
或:
$('.main').not('.right').css('background-color','red');
如果需要更复杂的条件与过滤器
函数:
$('.main').filter(function(){
return $(this).data('value') == 2 && this.innerHTML.length < 50;
}).css('background-color','red');
它将过滤出 .main
并且只保留它们的数据值
为2并且它们的 innerHTML.length < 50
。
It will filter out the result of .main
and maintain only element which their data-value
is 2 and their innerHTML.length < 50
.
如果您不知道其他类可以是 main
,但您希望只有 main
类的元素。
If you don't know what other classes could be to main
but you want the elements which has only the main
class.
$('.main').filter(function(){
return $.trim(this.className) == 'main';
}).css('background-color','red');
这篇关于如何使用jQuery过滤不需要的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文