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

时间:2015-03-14 04:25:05

标签: javascript jquery radio-button

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

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

1 个答案:

答案 0 :(得分:1)

使用

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

&#13;
&#13;
$(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');
});
&#13;
div.question_explanation {
  background-color: LightGray;
}
div.correct_answer_green {
  background-color: LightGreen;
}
&#13;
<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>
&#13;
&#13;
&#13;