jquery元素过滤器由css

时间:2010-05-11 16:17:28

标签: jquery

我想选择每个具有红色背景颜色的div。 这有可能在jquery吗?

<div style="background-color:red"></div>
<div style="background-color:white"></div>
<div style="background-color:red"></div>
<div style="background-color:yellow"></div>

谢谢

6 个答案:

答案 0 :(得分:19)

您可以使用jQuery过滤器:

$('div').filter(function() {
   return this.element.style['background-color'] == 'red';
});

但是,正如tvanfosson所说,正确的方法是为每个div分配一个CSS类,然后你可以使用jQuery这样调用对象(这是使用jQuery的首选方式):

$('.yourCSSClass');

答案 1 :(得分:18)

此代码也适用于标签的样式属性中定义的CSS:

$('div').filter(function() {
   return $(this).css('background-color') == 'red';
});

答案 2 :(得分:14)

$('div[style=background-color:red]');

答案 3 :(得分:7)

为什么这么难?更好的解决方案是使用CSS类为元素提供样式,然后您可以简单地使用基于类的选择器。

<style type="text/css">
    .alert {
       background-color: red;
    }
</style>

<div class="alert"></div>


$('.alert')....

答案 4 :(得分:3)

首先,我从不建议在页面元素上设置内嵌样式。在外部CSS文档中分配CSS类并控制背景颜色。

<div class="red"></div>
<div class="white"></div>
<div class="red"></div>
<div class="yellow"></div>

在你的CSS中:

.red {background-color:red;}
.white {background-color:white;}
.yellow {background-color:yellow;}

然后,通过使用:$('div.red')

可以轻松选择红色的

答案 5 :(得分:2)

如果您不想依赖标记上的某个style=xxx属性,我认为您需要自定义过滤器:

$('*').filter(function() { /* check the background color of this */ });