javascript - JQuery 调用 .elements 返回未定义
问题描述
我正在尝试使用 jQuery 遍历一组复选框。复选框是用 HTML 编写的,如下所示:
<div id="checkboxes">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="XXX" class="custom-control-input" id="a" value="XXX">
<label class="custom-control-label" for="a">XXX</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="XXX" class="custom-control-input" id="b" value="XXX">
<label class="custom-control-label" for="b">XXX</label>
</div>
...
</div>
我试图用这个(对按钮单击的响应的一部分)获取 JQuery 中的复选框数组:
var choices = document.getElementById("checkboxes").elements;
但是,当我调用 时for(let i = 0; i < choices.length; i++)
,控制台中出现错误:
Uncaught TypeError: Cannot read property 'length' of undefined
显然,该变量choices
未定义。我已经做了一些研究,但我找不到问题出在哪里,或者我可以通过其他方式获取复选框元素的数组。
解决方案
用于querySelectorAll()
定位特定的元素集合
var choices = document.querySelectorAll('#checkboxes input[type="checkbox"]');
choices.forEach( el => console.log(el.id, el.value) )
<div id="checkboxes">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="XXX" class="custom-control-input" id="a" value="XXX">
<label class="custom-control-label" for="a">XXX</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="XXX" class="custom-control-input" id="b" value="XXX">
<label class="custom-control-label" for="b">XXX</label>
</div>
</div>
推荐阅读
- c - C/Linux:如何将计算平均分配给线程?
- python - 烧瓶重定向需要 url 和 api 密钥
- linux - UDP 套接字接收缓冲区大小
- elasticsearch - 我应该从我的应用程序中查询哪个 elasitcsearch 节点
- c++ - 二进制表达式的无效操作数(常量点和常量点
- python-3.x - 使用 qsub 中的 .e 和 .o 文件作为 snakemake 中每个规则的日志
- java - 如何将 maven 插件上传到 Github 包?
- python - 我如何允许调平系统在某些级别添加角色?
- reactjs - 在渲染之外使用 React Router 功能
- python - 为什么对小数进行排序不起作用?