【发布时间】:2021-07-09 11:36:24
【问题描述】:
我有一个 jQuery 代码,用于检查哪个单选按钮被选中,然后将颜色更改为其中的一些。此外,我想在按下其中一个按钮后禁用按钮。我的问题是,当我检查例如“A”时,所有答案都变成红色,而不是“A”变成绿色,其他所有答案都变成红色。
$(function() {
$('.AncientQ11 [type="radio"]').on('change', function() {
$(document.getElementById("AncientQ1Ans1"))
.prev().addClass('green')
.siblings().addClass('red');
document.getElementById("AncientQ1Ans1").disabled = true;
document.getElementById("AncientQ1Ans2").disabled = true;
document.getElementById("AncientQ1Ans3").disabled = true;
document.getElementById("AncientQ1Ans4").disabled = true;
});
});
.red {color: red;}
.black {color: black;}
.green{color:green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="AncientQ11">
<label for="AncientQ1Ans1">A</label><br>
<input type="radio" id="AncientQ1Ans1" name="AncientQ1">
<label for="AncientQ1Ans2">B</label><br>
<!--Solution-->
<input type="radio" id="AncientQ1Ans2" name="AncientQ1">
<label for="AncientQ1Ans3">C</label><br>
<input type="radio" name="AncientQ1" id="AncientQ1Ans3">
<label for="AncientQ1Ans4">D</label>
<input type="radio" name="AncientQ1" id="AncientQ1Ans4">
</div>
【问题讨论】:
-
离题:
$(document.getElementById("AncientQ1Ans1"))->$("#AncientQ1Ans1") -
你的js/html怎么知道Q1Ans1是正确答案?您是否将其硬编码到 js 中?
-
您的问题是标签和收音机之间的“隐藏”
<br/>- 当我将您的代码转换为 sn-p 并运行它时,这一点变得很明显。 checkbox.prev = br,而不是标签。便宜/快速的解决方法是将.prev()更改为.prev().prev()- 更好的解决方案是修复您的布局 - 或者更好的是,使用$("label[for=AncientQ1Ans1").addClass("green")... -
是的。我为任何问题编写了相同的代码,但 id 不同。
-
哦,好吧,我不知道。我删除了 并且它有效。谢谢。
标签: javascript jquery radio-button