gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:34:53 25 4
gpt4 key购买 nike

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

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/jquery : add class if a radio button is selected and data attribute qualifies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29045448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com