选择一个元素,它的背景颜色在jQuery中不起作用

时间:2017-07-06 09:52:58

标签: javascript jquery

请检查我的代码。检查背景颜色的条件不起作用。

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>
&#13;
&#13;
&#13;

当我们处于警示背景颜色时,它正在工作。但我们无法匹配颜色。

2 个答案:

答案 0 :(得分:5)

你需要在每个逗号之后用rgb颜色代码(如rgb(255, 193, 0))给出一个空格。然后就行了。

&#13;
&#13;
$(function(){

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

});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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>