【HTML】之元素id名複雜化時,radio中checked無效的情況
阿新 • • 發佈:2019-01-02
背景:
最近在做一個小專案,教師(主要分為教師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');
});
程式碼如上所示。
完成
總結
發現問題,並千方百計地尋求解決問題的方法,才能更好的成長。