我的页面上有一个选择题。如果用户选择了正确的答案,我希望他们选择的说明从灰色变为绿色。无论选择什么,我都只能获得变为绿色的所有选择,而且似乎无法正确实现。非常感谢您的帮助,谢谢。

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>

关于javascript - JavaScript/jquery:如果选择了单选按钮并且数据属性合格,则添加类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29045448/

10-11 12:33
查看更多