我有一個包含兩列的表格:值和復選框。我想用選中的復選框識別最小值。我根據這個問題調整了設定,但改變了我識別復選框的方式從
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">
uj5u.com熱心網友回復:
您的代碼查看表中的所有行。您沒有考慮表的第一行是 thead。所以你的表格行比復選框多一個。
const trs = table.querySelectorAll("tbody tr");
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354523.html
標籤:javascript html
