我有输入:
<div id="my">
<input type="checkbox" value="1" name="names[]">
<input type="checkbox" value="2" name="names[]">
<input type="checkbox" value="3" name="names[]">
<input type="checkbox" value="4" name="names[]">
</div>
还有我的 JavaScript:
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", ($.inArray($(this).val(), initValues)));
});
现在我所有的复选框都被选中了。我必须如何更改代码以设置检查 initValues 数组中的值的 cckeckbox?
最佳答案
$.inArray 返回索引,而不是 bool 值。另外,parseInt你的值,因为当你拿起它时它被认为是字符串。
initValues=[1,2,3];
$('#my').find(':checkbox[name="names[]"]').each(function () {
$(this).prop("checked", $.inArray(parseInt($(this).val()), initValues) == -1 ? false : true );
});
关于javascript - 如果其值在数组中,如何设置选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600090/