目录
背景
最近在做一个小项目,教师(主要分为教师PC端和学生移动端)在PC端创建题目模板(包括选择题、填空题、简答题等),需要以json的形式提交到数据库。
在进行form表单提交的时候,会涉及到一个form多个相同name的情况(后端用php),所以就采取name=name[动态变量]来提交到后端,同时针对每个元素,都采取id=id[动态变量]的形式。
然而,学生在移动端进行答题的时候,提交完答案后,再次点击进来,会自动返回学生提交的答案(即自动选上选择题radio,自动填上填空题等的答案)。
问题
由于我这边用的是id=id[动态变量],所以在前端使用jQuery设置选择题的radio时,checked失效了。
网上的做法是把attr换成prop,老的attr存在一些bug,难以修复以至于提供一个新的方法prop。
可是,目前我这边还是无法使用prop更改id数组的checked。
index.html
<body>
<div class="part-one">
<div>
第一组的<label for="a" id="alabel">AAA</label>
<input type="radio" id="a[0]" name="choQues[0]" value="A">
</div>
<div>
第一组的<label for="b" id="blabel">BBB</label>
<input type="radio" id="b[0]" name="choQues[0]" value="B">
</div>
</div>
<hr><hr>
<div class="part-two">
<div>
第二组的<label for="a" id="alabel">AAA</label>
<input type="radio" id="a[1]" name="choQues[1]" value="A">
</div>
<div>
第二组的<label for="b" id="blabel">BBB</label>
<input type="radio" id="b[1]" name="choQues[1]" value="B">
</div>
</div>
<hr><hr>
<input id="button1A" type="button" value="选第一组的A">
<input id="button1B" type="button" value="选第一组的B">
<input id="button2A" type="button" value="选第二组的A">
<input id="button2B" type="button" value="选第二组的B">
</body>
index.js
$("#button1A").click(function(){
$('#a[0]').prop('checked','checked');
});
$("#button1B").click(function(){
$('#b[0]').prop('checked','checked');
});
$("#button2A").click(function(){
$('#a[1]').prop('checked','checked');
});
$("#button2B").click(function(){
$('#b[1]').prop('checked','checked');
});
代码如上所示。
单击任何一个按钮都没有效果。
修改
把id=id[动态变量]修改为id=id动态变量,取消了 []
index.html
<body>
<div class="part-one">
<div>
第一组的<label for="a" id="alabel">AAA</label>
<input type="radio" id="a0" name="choQues[0]" value="A">
</div>
<div>
第一组的<label for="b" id="blabel">BBB</label>
<input type="radio" id="b0" name="choQues[0]" value="B">
</div>
</div>
<hr><hr>
<div class="part-two">
<div>
第二组的<label for="a" id="alabel">AAA</label>
<input type="radio" id="a1" name="choQues[1]" value="A">
</div>
<div>
第二组的<label for="b" id="blabel">BBB</label>
<input type="radio" id="b1" name="choQues[1]" value="B">
</div>
</div>
<hr><hr>
<input id="button1A" type="button" value="选第一组的A">
<input id="button1B" type="button" value="选第一组的B">
<input id="button2A" type="button" value="选第二组的A">
<input id="button2B" type="button" value="选第二组的B">
</body>
index.js
$("#button1A").click(function(){
$('#a0').prop('checked','checked');
});
$("#button1B").click(function(){
$('#b0').prop('checked','checked');
});
$("#button2A").click(function(){
$('#a1').prop('checked','checked');
});
$("#button2B").click(function(){
$('#b1').prop('checked','checked');
});
代码如上所示。
完成
总结
发现问题,并千方百计地寻求解决问题的方法,才能更好的成长。