问题描述
我正在使用jQuery 3.5.1。我有这个HTML
<form>
<div><input type="radio" id="radio0" name="choice" >Text1</div>
<div><input type="radio" id="radio1" name="choice" >Text2</div>
<div><input type="radio" id="radio2" name="choice" >Text3</div>
<div><input type="radio" id="radio3" name="choice" >Text4</div>
我想更改单选按钮旁边的标签,所以我要这样做...
for (let i=0; i<choices.length; i++) {
$('#radio' + i).text(choices[i]);
$('#radio' + i).val(choices[i] == age ? CORRECT : INCORRECT);
$('#radio' + i).attr("checked",false);
}
但是,新标签不会出现在屏幕上。当我在Firefox中检查元素时(在Mac上),我看到了
<div><input type="radio" id="radio0" name="choice" value="incorrect">27
Text1</div>
<div><input type="radio" id="radio1" name="choice" value="incorrect">24
Text2</div>
<div><input type="radio" id="radio2" name="choice" value="incorrect">21
Text3</div>
<div><input type="radio" id="radio3" name="choice" value="correct">30
Text4</div>
<div id="Feedback" style="display: none;"></div>
<div>
<input type="button" value="Submit" id="submitAnswer">
</div>
所以以某种方式填充了元素(“ 27”,“ 24”等),但是旧元素也仍然存在(“ Text1”),并且屏幕上显示的是“ Text-”标签,而不是数字。构造HTML /编写jQuery以更改单选按钮标签的正确方法是什么?
解决方法
您是否考虑过为字符串使用标签?
<div><input type="radio" id="radio0" name="choice" ><label id="label0">Text1</label></div>
那你能做到吗?
for (let i=0; i<choices.length; i++) {
$('#label' + i).text(choices[i]);
$('#radio' + i).val(choices[i] == age ? CORRECT : INCORRECT);
$('#radio' + i).attr("checked",false);
}
,
将收音机包裹在<label>
中后,它的使用容易得多,因为整个标签都是事件的目标。
然后,如果您添加<span>
来换行,则它成为DOM查询的简单目标
const newVals = [111,444,777,999]
newVals.forEach((v,i) => {
const $input = $('#radio' + i).val(v).prop('checked',false);
$input.next('span').text(v);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>
<input type="radio" id="radio0" name="choice" >
<span>Text1</span>
</label>
</div>
<div><label><input type="radio" id="radio1" name="choice" ><span>Text2</span></label></div>
<div><label><input type="radio" id="radio2" name="choice" ><span>Text3</span></label></div>
<div><label><input type="radio" id="radio3" name="choice" ><span>Text4</span></label></div>