如何安排数组进行恒定循环?

问题描述 投票:0回答:1

我希望循环找到并使用我为超过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>
javascript arrays
1个回答
0
投票

您可以查询data-id与输入数据中的一个id匹配的元素。

const input = [
  {q: "58b988ff62279282090dd314"}, 
  {q: "58b988ff62279282090dc152"},
  {q: "58b988ff62279282090dbf09"}
];

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>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>

或者你可以在没有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';
  }
}); 
<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>
© www.soinside.com 2019 - 2024. All rights reserved.