【问题标题】:JQuery calling .elements returns undefinedJQuery 调用 .elements 返回未定义
【发布时间】:2020-10-18 21:38:30
【问题描述】:

我正在尝试使用 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 &lt; choices.length; i++) 时,控制台中出现错误:

Uncaught TypeError: Cannot read property 'length' of undefined

显然,变量choices 未定义。我做了一些研究,但我找不到问题出在哪里,或者我可以通过其他方式获取复选框元素的数组。

【问题讨论】:

  • 试图获取choices 长度的代码在哪里?另外,document.getElementById() 是纯 JS,而不是 jQuery。
  • 感谢指出,我已编辑

标签: javascript html jquery arrays checkbox


【解决方案1】:

使用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>

【讨论】:

    猜你喜欢
    • 2011-04-17
    • 1970-01-01
    • 2016-11-18
    • 2013-03-08
    • 2021-09-06
    • 2016-12-01
    • 2010-11-29
    • 2020-06-30
    • 1970-01-01
    相关资源
    最近更新 更多