Jquery查找类,值和更改背景颜色

Jquery find class, value and change background color

本文关键字:背景 颜色 查找 Jquery      更新时间:2023-09-26

所以我有这个代码

<div class="width100">
    <div class="width16 aux"><h1>ABC</br>A1</h1><p class="aux-status">50</p></div>
    <div class="width16 aux"><h1>ABC</br>B2</h1><p class="aux-status">24</p></div>
    <div class="width16 aux"><h1>ABC</br>C3</h1><p class="aux-status">24</p></div>
    <div class="width16 aux"><h1>DEF</br>1A</h1><p class="aux-status">24</p></div>
    <div class="width16 aux "><h1>ABC</br>D4</h1><p class="aux-status">0</p></div>
    <div class="width32 aux coomms">have: 12213</div>

    <div class="width16 aux clear"><h1>ABC</br>E5</h1><p class="aux-status">24</p></div>
    <div class="width16 aux"><h1>ABC</br>F6</h1><p class="aux-status">0</p></div>
</div>

现在我需要循环所有段落与类"aux-status"和检查值。如果值为<10,我需要将背景改为绿色,在10到20之间为橙色,在20以上为红色。

你知道怎么做吗?

$('.aux-status').each(function(index,value){
  var value1 = parseInt($(this).text(),10);
      if(value1  <10)
       $(this).css('background-color','green');
      else if(value1  > = 10 && value <=20)
       $(this).css('background-color','orange');
      else 
       $(this).css('background-color','red'); 
});
http://jsfiddle.net/FLsVT/2/

你可以得到

的文本如下:

$(document).ready(function(){
  $('.aux-status').each(function(){
  var value = parseInt($(this).text(),10);
  if(value  <10)
   $(this).css('background-color','black');
  else if(value  > = 10 )
   $(this).css('background-color','red');
  });
});

希望这对你有用

用这个…

$('.aux-status').each(function(){
    var value = parseInt($(this).text());
    if(value < 10){
         $(this).css('background-color', 'green');   
    }else if(value > 20){
        $(this).css('background-color', 'red');   
    }else{
        $(this).css('background-color', 'orange');   
    }
});

查看DEMO

.css方法接受一个函数作为第二个参数,因此您可以这样做:

$('.aux-status').css('background-color', function() {
    var value = parseInt($(this).text(), 10);
    if (value < 10) {
       return 'green';    
    } else if (value >= 10 && value <=20 ) {
       return 'orange';
    } else {
       return 'red';
    }
 });

小提琴演示。

$('.width100 .aux-status').each(function(){
    var myval = $(this).text();
    if(myval < 10){
        $(this).prev().css('background-color','green');
    }
    if(myval => 10 && myval < 21){
        $(this).prev().css('background-color','orange');
    }
    if(myval > 20){
        $(this).prev().css('background-color','red');
    }
});