在jQuery中选择具有背景颜色的元素不起作用

5
请检查我的代码。 检查背景颜色的条件不起作用。 https://jsfiddle.net/oL7tdL22/1/

$(function(){

$(".testing").each(function(){
   if($(this).css("background-color")=="rgb(255,193,0)"){
     alert("found");
   }
   else{
     alert("not found");
   }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="parent">
<div class="testing"  style="background-color:rgb(255,193,0)">
Test
</div>
</div>

<div class="parent">
<div class="testing"  style="background-color:rgb(220, 4, 81)">
Test
</div>
</div>


<div class="parent">
<div class="testing"  style="background-color:rgb(0, 186, 76)">
Test
</div>
</div>

当我们设置了警示背景色时,它是有效的。但我们无法匹配颜色。


当我运行警报时,每个逗号后面都有空格。添加空格似乎是解决方法。 - vi5ion
1
我删除了所有空格,它可以正常工作 jsFiddle - Ray Lloy
2个回答

5

在RGB颜色代码中,每个逗号后面都需要加上一个空格,例如rgb(255, 193, 0)。这样才能生效。

$(function(){

$(".testing").each(function(){
   if($(this).css("background-color")=="rgb(255, 193, 0)"){
     alert("found");
   }
   else{
     alert("not found");
   }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="parent">
<div class="testing"  style="background-color:rgb(255,193,0)">
Test
</div>
</div>

<div class="parent">
<div class="testing"  style="background-color:rgb(220, 4, 81)">
Test
</div>
</div>


<div class="parent">
<div class="testing"  style="background-color:rgb(0, 186, 76)">
Test
</div>
</div>


3
你需要用空格分隔rgb值,因为JQuery通过这种方式解析.css("background-color")值。
rgb(X, Y, Z)
      ▲  ▲

这是正确的代码:
if($(this).css("background-color")=="rgb(255, 193, 0)"){
   alert("found");
}

代码片段:

$(function(){
     $(".testing").each(function(){
        if($(this).css("background-color")=="rgb(255, 193, 0)")
          alert("found");
        else
          alert("not found");
     });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="parent">
    <div class="testing"  style="background-color:rgb(255,193,0)">Test</div>
</div>
<div class="parent">
    <div class="testing"  style="background-color:rgb(220, 4, 81)">Test</div>
</div>
<div class="parent">
    <div class="testing"  style="background-color:rgb(0, 186, 76)">Test</div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接