有如下html,
<em>+5.0</em>
<em>+3.2</em>
<em>-2.4</em>
<em>-4.6</em>
我想根据条件为每个数字设置颜色。 如果数字大于 0,则颜色为红色。 其他人会是蓝色的。输出将是
+5.0 (red color)
+3.2 (red color)
-2.4 (blue color)
-4.6 (blue color)
我如何使用 jQuery 做到这一点?
我尝试过的
if ($('em').text() > 0){
$(this).css('color', 'red');
}
但是 $('em').text()
不是一个元素,我无法正确应用样式。
我该怎么做?
最佳答案
您需要使用 .each()
, 维护this
上下文
$('em').each(function(){
if (+$(this).text() > 0){
$(this).css('color', 'red');
}
})
或者,.filter()
可以使用。
$('em').filter(function(){
return +$(this).text() > 0;
}).css('color', 'red')
注意:我使用 +
将文本转换为数字。
关于javascript - 使用 jQuery 按条件将样式设置为 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37108589/