Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript/jQuery从列表中选择复选框_Javascript_Jquery - Fatal编程技术网

使用javascript/jQuery从列表中选择复选框

使用javascript/jQuery从列表中选择复选框,javascript,jquery,Javascript,Jquery,如何选择id在列表或数组中的复选框?假设我有一个ID列表 var selected = 'chkbx_0,chkbx_3' <div id="optionList"> <input id="chkbx_0" type="checkbox" name="c_n_0" />Option 1 <input id="chkbx_1" type="checkbox" name="c_n_1" />Option 2 <input id="chkbx_2" typ

如何选择id在列表或数组中的复选框?假设我有一个ID列表

var selected = 'chkbx_0,chkbx_3' 

<div id="optionList">
<input id="chkbx_0" type="checkbox" name="c_n_0" />Option 1
<input id="chkbx_1" type="checkbox" name="c_n_1" />Option 2
<input id="chkbx_2" type="checkbox" name="c_n_2" />Option 3
<input id="chkbx_3" type="checkbox" name="c_n_3" />Option 4
</div>
因此,当我运行函数时,我希望列表中的任何内容仅在该特定div中选择
谢谢

如果您可以将列表设置为一个数组,那么它将变得非常简单:

var idList = ["chkbx_0", "chkbx_3"];
for (var i = 0; i < idList.length; i++)
{
  $("#" + idList[i]).prop("checked", true);
}
代码解释

var selected_arr=selected.split',';:这里,我将逗号分隔的项拆分为一个数组

$('#optionList input').each(function(){
    if( selected_arr.includes($(this).attr('id')) )
    {
      $(this).prop('checked', true);
    }
});
在上面的函数中,我们将遍历指定div中的所有输入复选框,并检查它们的id是否存在于我们创建的数组中。如果存在,则选中该复选框

所选变量='chkbx_0,chkbx_3'; var selected_arr=selected.split','; $'optionList input'。每个函数{ 如果选中,则包含$this.attr'id' { $this.prop'checked',true; } }; 选择1 选择2 选择3 选择4 所选变量='chkbx_0,chkbx_3'; //使用split函数拆分为数组 var arr=selected.split','; //在这里可以找到数组的长度 var len=阵列长度; //for循环检查数组中的每个字符串
forvar i=0;我不知道最终结果应该是什么。所以应该选择checkbx_0和checkbx_3?最终结果将显示chkbx_0和chkbx_3 checked,因为它们在所选字符串中或使其成为一个数组-所以应该选择checkbx_0和checkbx_3制作数组,并运行循环以获取单个id,使用jquery,您可以设置特定的复选框来设置checked集成代码段不需要JSFIDLE。另外,考虑一下解释一下你的答案。
$('#optionList input').each(function(){
    if( selected_arr.includes($(this).attr('id')) )
    {
      $(this).prop('checked', true);
    }
});