Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is usage from multifiltering with jQuery useful?

Tags:

jquery

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

like image 811
bernte Avatar asked Jun 06 '26 13:06

bernte


2 Answers

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');
    }
});
like image 85
Jason P Avatar answered Jun 10 '26 08:06

Jason P


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().
like image 42
David Thomas Avatar answered Jun 10 '26 08:06

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!