我正在构建一个简单的函数,该函数根据元素的值分配包含颜色的类。我的问题是,为了做到这一点,我必须遍历我的元素吗?
这是我的jsfiddle
HTML
<div>
<ul>
<li class="MyScore">90</li>
<li class="MyScore">82</li>
<li class="MyScore">77</li>
<li class="MyScore">66</li>
<li class="MyScore">62</li>
<li class="MyScore">50</li>
<li class="MyScore">42</li>
<ul>
</div>
CSS
.good{
background-color: green;
}
.okay{
background-color: yellow;
}
.bad{
background-color: red;
}
JS
function scoreColor(score){
var score = document.querySelector('.MyScore').innerHTML;
var scoreColor = document.querySelector('.MyScore');
if(score > 85){
scoreColor.className + ' good';
console.log('good');
} else if(score > 65 && score < 85 ){
scoreColor.className + ' okay';
console.log('okay');
} else {
scoreColor.className + ' bad';
console.log('bad');
}
}
scoreColor();
由于
答案 0 :(得分:0)
尝试一下:
for (let x of Array.from(document.querySelectorAll('.MyScore'))) {
let score = parseInt(x.innerHTML);
if (score > 85){
x.className = 'good';
} else if (score > 65 && score < 85){
x.className = 'okay';
} else {
x.className = 'bad';
}
}
querySelectorAll
返回所有匹配元素的迭代器(Array.from
只需将其转换为数组)。
答案 1 :(得分:0)
试试这个,看看里面的评论(fiddle):
function scoreColor() {
var scores = document.querySelectorAll('.MyScore'); // get all elements with .Myscore
Array.prototype.forEach.call(scores, function (item) { // iterate the elements
var score = parseInt(item.innerText, 10); // get the value from the text and parse it
if (score > 85) {
item.classList.add('good'); // add good to the item classList
console.log('good');
} else if (score > 65 && score < 85) {
item.classList.add('okey'); // add okey to the item classList
console.log('okay');
} else {
item.classList.add('bad'); // add bad to the item classList
console.log('bad');
}
});
}
scoreColor();