我希望循环找到并使用我为超过1000个数据直接编写的正确代码,而不是逐个尝试。此编码的目的应该是将绿色背景应用于循环finallt找到的正确数据ID。
var answerKey = [{
q: "58b988ff62279282090dd314"
}, {
q: "58b988ff62279282090dc152"
}, {
q: "58b988ff62279282090dbf09"
}
// etc.
];
var questionTxt = $(this).find('data-id');
questionTxt.each(function() {
$(this).css("background", "lime");
return false; // End loop
});
function getAnswer(questionText) {
for (var J = answerKey.length - 1; J >= 0; --J) {
var zRegExp = new RegExp(answerKey[J].q, 'i');
if (zRegExp.test(questionText))
return answerKey[J].q;
}
return null;
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question-text" class="question sp-element border-radius active">Which one is the biggest country in the world ?</div>
<ul class="answers" id="answers">
<li data-id="58b988ff62279282090dc14f" class="answer sp-element border-radius active">Germany</li>
<li data-id="58b988ff62279282090dc150" class="answer sp-element border-radius active">Swiss</li>
<li data-id="58b988ff62279282090dc152" class="answer sp-element border-radius active">China</li>
<li data-id="58b988ff62279282090dc151" class="answer sp-element border-radius active">Belgium</li>
</ul>
&#13;
答案 0 :(得分:0)
您可以查询data-id
与输入数据中的某个ID匹配的元素。
const input = [
{q: "58b988ff62279282090dd314"},
{q: "58b988ff62279282090dc152"},
{q: "58b988ff62279282090dbf09"}
];
input.forEach(({q}) => $(`[data-id="${q}"]`).css("background", "lime"));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Which one is the biggest country in the world ?</div>
<ul>
<li data-id="58b988ff62279282090dc14f">Germany</li>
<li data-id="58b988ff62279282090dc150">Swiss</li>
<li data-id="58b988ff62279282090dc152">China</li>
<li data-id="58b988ff62279282090dc151">Belgium</li>
</ul>
&#13;
或者你可以在没有jQuery的情况下获得相同的结果,如下所示:
const input = [
{q: "58b988ff62279282090dd314"},
{q: "58b988ff62279282090dc152"},
{q: "58b988ff62279282090dbf09"}
];
input.forEach(({q}) => {
const res = document.querySelector(`[data-id="${q}"]`);
if(res) {
res.style.background = 'lime';
}
});
&#13;
<div>Which one is the biggest country in the world ?</div>
<ul>
<li data-id="58b988ff62279282090dc14f">Germany</li>
<li data-id="58b988ff62279282090dc150">Swiss</li>
<li data-id="58b988ff62279282090dc152">China</li>
<li data-id="58b988ff62279282090dc151">Belgium</li>
</ul>
&#13;