0

我有以下类型的 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);
}
});

当我只有一个“笔记”课程时,它运作良好。然而,有几个“笔记”类它不起作用。解决这个问题的最佳方法是什么?

谢谢

4

2 回答 2

0

您必须使用该类迭代所有项目:

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 的新手。

于 2018-06-18T16:42:28.777 回答
0

1)以下行将返回“31”,我想这不是你所期望的:

var score = parseInt(jQuery('.note h4 span').text().trim());

2)以下行将影响所有在“h4”中为“span”且具有类“note”的DOM元素,我想这不是你所期望的:

 jQuery('.note h4 span').css('color', color);

You have to iterate over an oject with all spans elements in order to change color for each of them with a jquery "each" loop.

Check the following JsFiddle :

https://jsfiddle.net/2ho83qeg/

于 2018-06-18T17:16:33.167 回答