3

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

4

2 回答 2

3

这种类型的问题更适合http://codereview.stackexchange.com

但是,我不会两次过滤列表,而是只迭代一次并同时检查两个条件。

$('.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');
    }
});
于 2013-08-26T15:51:42.920 回答
2

我个人建议:

$('.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 小提琴演示

其中的匿名函数addClass()将遍历选择器返回的元素,并且在每次迭代中,$(this)/this将引用当前元素;这样做的好处是您需要调用更少的 jQuery 方法(这减少了在同一组元素上迭代/重复迭代所花费的时间)。

参考:

于 2013-08-26T15:53:48.163 回答