如何更改同一ID的多个文本的颜色?

时间:2014-05-25 13:40:08

标签: jquery

基本上,我要做的是改变页面上多个事物的“点”的颜色。如果它是正面的,我希望它是绿色和红色,如果它是负面的。对于点值,我将它们放在

标签中,如

<p id="points">9843</p>
到目前为止,还有两个。我使用以下jquery代码

让它们都改变了颜色
var $points = $('#points');

if(parseInt($points.html())>0){
    $('#points:first-child').removeClass('red').addClass('green');
}
else{
    $('#points:first-child').removeClass('green').addClass('red');
}

但是,如果其中一个数字为负数而另一个数字为正数,则它们保持相同的颜色。没有一个变成红色,一个像我想要的那样保持绿色。我尝试使用$(this).removeClass .....并且这也不起作用。是否有一个选择器可以“改变

的文本内容的颜色
<p>

id为#points“?

1 个答案:

答案 0 :(得分:2)

假设您将选择器更改为类名,例如.points,则以下方法有效:

// selecting the 'p' elements with the className of 'points':
$('p.points')
// removing both the 'red' and 'green' classNames:
.removeClass('green red')
// using the anonymous function of addClass() to specify which class to add:
.addClass(function(){
    // using $.trim() to remove leading/trailing white-space from the text,
    // if that text is a number greater than 0, we return the 'green' className,
    // otherwise the 'red' className:
    return parseFloat($.trim($(this).text())) > 0 ? 'green' : 'red';
});

JS Fiddle demo

如果您想在添加.points / green classNames之前确保red元素包含数字:

$('p.points').removeClass('green red').addClass(function(i,c){
    var text = parseFloat($.trim($(this).text()));
    // using jQuery.isNumeric() to assess whether the passed variable
    // is, or represents, a number (true if it does, false if it does not):
    if ($.isNumeric(text)) {
        return text > 0 ? 'green' : 'red';
    }
});

JS Fiddle demo

参考文献: