Javascript 通过Jquery根据某个值设置复选框
我想根据Javascript 通过Jquery根据某个值设置复选框,javascript,jquery,dom,Javascript,Jquery,Dom,我想根据student.student\u type的值设置一个复选框,其中student是我在ajax调用和student之后得到的json对象。student\u type可以是0,1,2和3中的一个,其中0=>常规,1=>对应,等等 <input id="student_type_" type="checkbox" value="Regular" />Regular <input id="student_type_" type="checkbo
student.student\u type
的值设置一个复选框,其中student是我在ajax调用和student之后得到的json对象。student\u type
可以是0,1,2和3中的一个,其中0=>常规,1=>对应,等等
<input id="student_type_" type="checkbox" value="Regular" />Regular
<input id="student_type_" type="checkbox" value="Correspondence" />Correspondence
<input id="student_type_" type="checkbox" value="Exchange"/>Exchange
<input id="student_type_" type="checkbox" value="Dual" />Dual
常规
通信
交换
二重的
由于生成的html中所有复选框的ID都相同,因此我无法决定如何执行此操作。是否有任何方法可以使用复选框的值来实现该目的?请提供帮助。ID必须是唯一的,因此您应该为元素指定一个公共类:
<input class="student_type_" type="checkbox" value="Regular" />Regular
<input class="student_type_" type="checkbox" value="Correspondence" />Correspondence
<!-- ... -->
如果您更改元素的顺序,当然这将不再有效。您可能希望使用数字值作为复选框的实际值:
<input class="student_type_" type="checkbox" value="0" />Regular
<!-- ... -->
或者,如果无法更改该值,则可以使用数组进行映射:
var types = ['Regular', 'Correspondence', /*...*/];
$('.student_type[value="' + types[student.student_type] + '"]').prop('checked', true);
因为学生只能是一种类型,你可能想考虑使用单选按钮代替复选框。
(a)。(b) ID必须是唯一的。ID必须是唯一的,并尝试根据值选中复选框$('.student_type[value="' + student.student_type + '"]').prop('checked', true);
var types = ['Regular', 'Correspondence', /*...*/];
$('.student_type[value="' + types[student.student_type] + '"]').prop('checked', true);