JavaScript / jquery:如果选择了单选按钮并且数据属性符合条件,则添加 class

JavaScript / jquery: add class if a radio button is selected and data attribute qualifies

我有一个包含多项选择题的页面。如果用户选择了正确的答案,我希望他们选择的解释从灰色变为绿色。无论选择什么,我都只能让所有的选择变绿,而且似乎无法做到这一点。非常感谢帮助,谢谢。

html

<li class='test-questions'>
  <input data-correct="true" id="answer_id_1" name="answer_id" type="radio" value="1" />
   A) I am the correct answer!
  <div class='question_explanation'>
    <p>Correct. This is an explanation of the correct answer.</p>
  </div>
</li>

<li class='test-questions'>
  <input data-correct="false" id="answer_id_2" name="answer_id" type="radio" value="2" />
   B) I am an incorrect answer.
  <div class='question_explanation'>
    <p>Incorrect. This is an explanation why the answer is incorrect.</p>
  </div>
</li>

css

div.question_explanation {
background-color: LightGray;
}

div.correct_answer_green {
background-color: LightGreen;
}

错误的javascript/jquery 函数

$("input[name*='answer_id']").each(function() {
  if ($(this).data('correct') === true && $(this).is(':checked')) {
  $('div.question_explanation').addClass('correct_answer_green');
  }
});

如果您愿意,可以在 coffeescript 中使用相同的错误函数

$("input[name*='answer_id']").each ->
  if $(this).data('correct') == true and $(this).is(':checked') 
    $('div.question_explanation').addClass 'correct_answer_green'
  return

使用

//Bind change event
$("input[name*='answer_id']").change(function() {
    //If condition
    if ($(this).data('correct') === true && $(this).is(':checked')) {
        $(this)
            .closest('li') //Find parent li
            .find('div.question_explanation') //find your div
            .addClass('correct_answer_green');
    }
}).trigger('change'); //Trigger on page load

$(document).ready(function() {
  $("input[name*='answer_id']").change(function() {
    if ($(this).data('correct') === true && $(this).is(':checked')) {
      $(this).closest('li').find('div.question_explanation').addClass('correct_answer_green');
    }
  }).trigger('change');
});
div.question_explanation {
  background-color: LightGray;
}
div.correct_answer_green {
  background-color: LightGreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class='test-questions'>
    <input data-correct="true" id="answer_id_1" name="answer_id" type="radio" value="1" />A) I am the correct answer!
    <div class='question_explanation'>
      <p>Correct. This is an explanation of the correct answer.</p>
    </div>
  </li>

  <li class='test-questions'>
    <input data-correct="false" id="answer_id_2" name="answer_id" type="radio" value="2" />B) I am an incorrect answer.
    <div class='question_explanation'>
      <p>Incorrect. This is an explanation why the answer is incorrect.</p>
    </div>
  </li>
</ul>