i got this code
$('.pBwarn div').filter(function(index){
return parseInt(this.innerHTML) > 60;
}).addClass("pB_yellow");
$('.pBwarn div').filter(function(index){
return parseInt(this.innerHTML) > 80;
}).addClass("pB_red");
and want to know if it is useful? or maybe another way to realize this.
i want to change the green bar to yellow when percentage is larger than 60 (id="max60")
and change it to red if percentage is larger than 80 (id="max80")
just want to say that the script is running perfect. i only asking if there is potential for improvement :D
you can check the DEMO for a better understanding
This type of question is better suited for http://codereview.stackexchange.com.
However, instead of filtering the lists twice, I would just iterate once and check for both conditionals together.
$('.pBwarn div').each(function() {
var val = parseInt(this.innerHTML, 10);
if (val > 80) {
$(this).addClass('pB_red');
} else if (val > 60) {
$(this).addClass('pB_yellow');
}
});
I'd personally suggest:
$('.pBwarn div').addClass(function(){
var num = parseInt((this.textContent || this.innerText),10);
if (num > 80) {
return 'pB_red';
} else if (num > 60) {
return 'pB_yellow';
}
});
JS Fiddle demo.
The anonymous function within addClass() will iterate over the elements returned by the selector, and, in each iteration, $(this)/this will refer to the current element; the benefit of this is that you need to call fewer jQuery methods (which reduces the time spent iterating/reiterating over the same set of elements).
References:
addClass().If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With