亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JQuery 調用 .elements 返回未定義

JQuery 調用 .elements 返回未定義

慕無忌1623718 2022-10-21 15:41:32
我正在嘗試使用 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未定義。我已經做了一些研究,但我找不到問題出在哪里,或者我可以通過其他方式獲取復選框元素的數組。
查看完整描述

1 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

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



查看完整回答
反對 回復 2022-10-21
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號