在jQuery中检查具有特定列表值的复选框的最快方法

Fastest way to checked checkboxes that have a value of specific list in jQuery

本文关键字:复选框 方法 列表 jQuery 检查      更新时间:2023-09-26

这是我的HTML Dom:

<input type="checkbox" class="chk-act" name="actionChk" value="17">
<input type="checkbox" class="chk-act" name="actionChk" value="18">
<input type="checkbox" class="chk-act" name="actionChk" value="19">
<input type="checkbox" class="chk-act" name="actionChk" value="20">
<input type="checkbox" class="chk-act" name="actionChk" value="21">

我有一个jQuery脚本,它通过ajax返回了一个JSon响应:

["18","20","21"]

该列表最多可以有200名成员。所以我很想找出在返回响应时,最快的方法来选中上面列表中有值的复选框。你的建议是什么?

在此上混合jQuery

arr = ["18","20","21"];
$("input:checkbox").prop('checked', false); //If you need to uncheck other boxes too
$.each(arr, function(k,v) {       
   $("input[value='""+v+"'"]").prop('checked', true);
});

演示1 |演示2:删除所有其他检查

最快的方法是将id标识符添加到复选框列表中。例如

<input type="checkbox" class="chk-act" name="actionChk" value="17" id='chk-act-17' />
//incidentally, I hope the lack of a closing '/' was an oversight
//when you get your JSON response, in your ajax success or done methods
var resp = ["12", "232"],
    respLength = resp.length;
for(var i = 0; i < respLength; i += 1){
    $('#chk-act-' + resp[i]).prop('checked', true);
    //if your are using jquery 1.7+ that is, otherwise use, 
    $('#chk-act-' + resp[i]).attr('checked', 'checked');
}

JS性能测试

比较目前的两个答案,如果采用更丑陋的"id"实现,OP对"最快"的要求会更好
Js Perf

FIddle已添加

JS FIddle

来自fiddle的张贴代码-

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
    checkboxes = $('.chk');
checkboxes.each(function(i, item){
    $(this).prop('checked', false);
});
arr.forEach(function(item, i) {
    $('#chk_' + item).prop('checked', true);
});

您可以attrprop检查复选框:

试试这个:

 arr = ["18","20","21"];
for(var i=0; i<arr.length; i++)
 {
    if(!$("input[value="+arr[i]+"]").is(':checked'))
    { 
        $("input[value="+arr[i]+"]").attr('checked', 'checked');
    }
 }

演示:http://jsfiddle.net/tU8TP/5/