jquery元素过滤器由css

sal*_*ane 15 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>
Run Code Online (Sandbox Code Playgroud)

谢谢

Mat*_*dic 20

此代码也适用于在标记的style属性中定义的CSS :

$('div').filter(function() {
   return $(this).css('background-color') == 'red';
});
Run Code Online (Sandbox Code Playgroud)


djd*_*d87 19

您可以使用jQuery过滤器:

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

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

$('.yourCSSClass');
Run Code Online (Sandbox Code Playgroud)


Gab*_*abe 14

$('div[style=background-color:red]');
Run Code Online (Sandbox Code Playgroud)

  • 仅在标签上有style属性时才有效 (11认同)
  • 没有错,只是值得指出,以防有人使用这个没有意识到这一点.另外,如果样式标记的格式不完全像`background-color:red`那么这将不匹配 (7认同)
  • @ThiefMaster - 我在上面的示例html中回答了这个问题. (3认同)
  • 回答了我自己的评论:您需要使用双反斜杠进行转义,并且冒号(`:`)也应转义:jQuery('div [style = color \\ :: \\#AABBCC]` (2认同)

tva*_*son 7

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

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

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


$('.alert')....
Run Code Online (Sandbox Code Playgroud)