我有以下类型的 html 代码:
<div class="note">
<h4>
<span>3</span>
</h4>
</div>
<div class="note">
<h4>
<span>1</span>
</h4>
</div>
我正在使用 JS 来根据值设置跨度文本的样式:
jQuery(function () {
// Score Color
var score = parseInt(jQuery('.note h4 span').text().trim());
var color = 'red';
if (!isNaN(score)) {
if (score >= 3) {
color = 'orange';
}
if (score >= 4) {
color = 'green';
}
jQuery('.note h4 span').css('color', color);
}
});
当我只有一个“笔记”类时,它工作得很好。但是,对于几个“注释”类,它不起作用。解决此问题的最佳方法是什么?
谢谢
最佳答案
您必须使用该类迭代所有元素:
jQuery(function () {
// Score Color
$('.note h4 span').each(function () {
var score = parseInt($(this).text().trim());
var color = 'red';
if (!isNaN(score)) {
if (score >= 3) {
color = 'orange';
}
if (score >= 4) {
color = 'green';
}
}
//Just put this outside the if.
//And use keyword this
jQuery(this).css('color', color);
});
});
.each()迭代对象上的所有元素。
$('.note h4 span')
返回与该选择器对应的元素列表。
如果我的解释有任何不正确之处,请告诉我,我也是 JQuery 的新手。
关于javascript - 根据值自定义颜色(多次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913916/