简体   繁体   中英

Jquery find class, value and change background color

So I have this code

<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>

Now i need to loop throughall paragraphs with class "aux-status" and check value. If value is <10 i need to change background to green, between 10 and 20 to orange and above 20 to red.

Any ideas how to do that?

$('.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/

you can get the text of

as below:

$(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');
  });
});

Hope this will work for you

Use this...

$('.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');   
    }
});

See this DEMO

.css method accepts a function as the second parameter, so you could do with:

$('.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';
    }
 });

The fiddle demo.

$('.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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM