簡體   English   中英

未捕獲的類型錯誤:無法讀取未定義的屬性(讀取“類型”)

[英]Uncaught TypeError: Cannot read properties of undefined (reading 'type')

我有一個包含兩列的表格:值和復選框。 我想用選中的復選框識別最小值。 我從這個問題調整了設置,但改變了我從document.getElementsByTagName('input')querySelectorAll(".myCheckbox")識別復選框的方式。 當我添加一個額外的輸入字段時,最初的方式成為一個問題(這就是我在下面包含它的原因)

但是,該函數會拋出Uncaught TypeError: Cannot read properties of undefined (reading 'type')

怎么了?

 function smallestWeight() { let values = []; const ele = document.querySelectorAll(".myCheckbox"); let table = document.getElementById("myTable"); let trs = table.getElementsByTagName("tr"); for (i = 0, len = trs.length; i < len; i++) { if (ele[i].type == 'checkbox' && ele[i].checked == true) { values.push(parseFloat(trs[i].cells[0].innerHTML)); } } } const btn = document.getElementById("click"); btn.addEventListener("click", function() { smallestWeight(); })
 <table id="myTable"> <thead> <tr> <th>value</th> <th>include</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td> </tr> <tr> <td>2.2</td> <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td> </tr> <tr> <td>3.3</td> <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td> </tr> <tr> <td>4.4</td> <td><input type="checkbox" class="myCheckbox" id="include" value="include" checked></td> </tr> </tbody> </table> <button id="click">Click</button><br> <input type="number">

您的代碼查看表中的所有行。 您沒有考慮表的第一行是 thead。 所以你的表格行比復選框多一個。

const trs = table.querySelectorAll("tbody tr");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM