我目前正在尝试创建一个多项选择活动,用户可以通过旁边的单选按钮选择其中一个答案。我已经能够通过明确写出代码来改变单选按钮:
$("#choice0").on('click', function(){
$("input[name=radioAwnser][value=0]").attr("checked","checked");
console.log("clicked a");
});
$("#choice1").on('click', function(){
$("input[name=radioAwnser][value=1]").attr("checked","checked");
console.log("clicked b");
});
$("#choice2").on('click', function(){
$("input[name=radioAwnser][value=2]").attr("checked","checked");
console.log("clicked c");
});
但是,我不一定知道会有多少答案。当我试着写一些更灵活的东西时:
function setUpAwnsers(){
for(var i = 0; i<=3 ; i++){
console.log("#choice" + i);
$("#choice" + i).on('click', function(){
$("input[name=radioAwnser][value=" + i +"]").attr("checked","checked");
console.log("clicked");
});
}
}
控制台响应&#34;点击&#34;当我点击div时,单选按钮不会改变。
我有什么简单的遗漏,或者是解决这个问题的更好方法吗?
答案 0 :(得分:1)
你不应该使用JavaScript:你需要的只是......不爱,但是<label>
代替<div>
<input type="radio" id="choice1" />
<label for="choice1">The content from your div here</label>
<input type="radio" id="choice2" />
<label for="choice2">The content from your div here</label>
标签的使用将为您提供更多优势:当用户点击标签时,也会为收音机发出点击事件。 div解决方案不会给你这个。
要了解详情,请参阅label reference
答案 1 :(得分:0)
不要在循环中绑定事件,只需使用 start with selector
添加事件处理程序$(document).on("click", "[id^=choice]", function () {
var no = this.id.replace("choice","");
$("input[name=radioAwnser][value=" + no + "]").prop("checked", true);
});
<强> DEMO 强>
如果你想循环跟随这个,但它不是很好的标准方式
function setUpAwnsers(){
for(var i = 0; i<=3 ; i++){
console.log("#choice" + i);
$(document).on("click","#choice" + i, function(){
var no = this.id.replace("choice","");
$("input[name=radioAwnser][value=" + no +"]").prop("checked",true);
console.log("clicked");
});
}
}
答案 2 :(得分:0)
一个可能的问题是,由于您在for循环中订阅了click事件,并尝试在事件处理程序中使用值i
,因此i
的值始终是最后一个值(因为它不是本地范围的)。试试这个:
function setUpAwnsers(){
for(var i = 0; i<=3 ; i++){
console.log("#choice" + i);
$("#choice" + i).on('click', function(i){
$("input[name=radioAwnser][value=" + i +"]").attr("checked","checked");
console.log("clicked");
}.bind(null, i));
}
}