我有4个data-id
属性,其中所有4个文本字段都是可选的。我想获得具有最大值的列表项的data-id
,并将背景颜色更改为lime
。
我不想改变较小的值。 样本值:(5-6-7-8),但我有100个这样的数字。
const input = [
{q: "5"},
{q: "6"},
{q: "7"},
{q: "8"}
];
input.forEach(({q}) => $(`[data-id$="${q}"]`).css("background", "lime"));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question-text" class="question">Whats your favorite colour?</div>
<ul class="answers" id="answers">
<li data-id="5" class="answer">Blue</li>
<li data-id="6" class="answer">Red</li>
<li data-id="7" class="answer">Yellow</li>
<li data-id="8" class="answer">Purple</li>
</ul>
&#13;
答案 0 :(得分:1)
这是一个相当常见的&#34;数组max&#34;问题,使用DOM应用程序。您可以使用Array.reduce()
Doc查找最大值,如下所示:
maxData = $(".answers li[data-id]").get ().reduce ( (maxObj, crrntNode) => {
var idVal = parseInt ( $(crrntNode).data("id"), 10);
if (idVal > maxObj.value) {
maxObj.value = idVal;
maxObj.node = crrntNode;
}
return maxObj;
},
{value: 0, node: null}
);
$("body").append (`<p>The highest data-id value was ${maxData.value}.</p>`)
$(maxData.node).css ("background", "lime");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question-text" class="question">Whats your favorite colour?</div>
<ul class="answers" id="answers">
<li data-id="5" class="answer">Blue</li>
<li data-id="6" class="answer">Red</li>
<li data-id="7" class="answer">Yellow</li>
<li data-id="8" class="answer">Purple</li>
</ul>
&#13;
请注意data-
属性与jQuery的.data()
函数之间的关系。
答案 1 :(得分:1)
答案 2 :(得分:1)
您的第一笔业务显然是在将字符串转换为实际数字时按q
值减少对象数组。之后,您会通过Max.max
找到最高的数字。无需在此处循环列表项。您可以简单地使用jQuery选择器并在数据属性中插入最高数字:
const input = [
{q: "5"},
{q: "6"},
{q: "7"},
{q: "8"}
];
const nums = input.reduce((prev, {q}) => {
return [...prev, +q];
}, []);
const highestNum = Math.max(...nums);
$(`[data-id="${highestNum}"`).css('background-color', 'lime');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question-text" class="question">Whats your favorite colour?</div>
<ul class="answers" id="answers">
<li data-id="5" class="answer">Blue</li>
<li data-id="6" class="answer">Red</li>
<li data-id="7" class="answer">Yellow</li>
<li data-id="8" class="answer">Purple</li>
</ul>
&#13;