使用 jquery 检查多个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18614731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check multiple checkboxes using jquery
提问by Sohil Desai
I have an array something like
我有一个类似的数组
var values = ['1','3','4','5'];
I have the list of checkboxes
我有复选框列表
<div id='list'>
<input type='checkbox' value='1' />
<input type='checkbox' value='2' />
<input type='checkbox' value='3' />
<input type='checkbox' value='4' />
<input type='checkbox' value='5' />
<input type='checkbox' value='6' />
<input type='checkbox' value='7' />
<input type='checkbox' value='8' />
<input type='checkbox' value='9' />
<input type='checkbox' value='10' />
</div>
now I want to select checkboxes whose values lies within array values. I have done this
现在我想选择其值位于数组值内的复选框。我已经这样做了
for(var i = 0; i < values.length; i++)
$("#list [value=" + values[i] + "]").attr("checked", "checked");
it is working fine but can I do it without for loop.
它工作正常,但我可以在没有 for 循环的情况下做到这一点。
Thank you in advance to helpers.
在此先感谢帮助者。
回答by Arun P Johny
回答by Blazemonger
You could do this even more succinctly with a single combined selector:
您可以使用单个组合选择器更简洁地执行此操作:
$('#list [value="'+values.join('"],[value="')+'"]').prop('checked',true);
Which produces a selector like:
它产生一个选择器,如:
$('#list [value="1"],[value="3"],[value="4"],[value="5"]')
回答by Selvakumar Arumugam
You could use filter
like below, but it is same as for
loop though..
你可以filter
像下面这样使用,但它与for
循环相同..
$('#list :checkbox').filter(function () {
return $.inArray(this.value, values) >= 0;
}).prop('checked', true);
回答by Daniel
You can replace your for-loop with $.each
你可以用 $.each 替换你的 for 循环
JQuery
查询
$.each(values, function() {
$("#list [value=" + this + "]").attr("checked", "checked");
});