我需要从矩阵单元格中获取不唯一的值。这个模型是原始模型的简化,这是一个巨大的矩阵,这就是为什么我把enfasis放在这个:document.getElementById(“myTable”)。rows [0] .cells [0] .XXXXXX。
目标:我应该在该指令中使用什么属性或方法来获取复选框(true / false)或(1,0)的值。
谢谢!!!!
<!DOCTYPE html>
<html>
<head>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Tratando de obtener valores de los checkbox dentro de una tabla.</p>
<table id="myTable">
<tr>
<td id='C1'> <input type='checkbox' checked='checked'> </td>
<td id='C2'> <input type='checkbox' checked='checked'> </td>
</tr>
<tr>
<td id='C3'> <input type='checkbox' checked='checked'> </td>
<td id='C4'> <input type='checkbox' checked='checked'> </td>
</tr>
</table>
<p id="print1"></p>
<p id="print2"></p>
<p id="print3"></p>
<p id="print4"></p>
<br>
<button onclick="myFunction()">Intentarlo</button>
<script>
function myFunction() {
document.getElementById("print1").innerHTML = document.getElementById("myTable").rows[0].cells[0];
}
</script>
</body>
</html>
复选框的已选中/未选中状态存储在其checked
属性中。请注意,你得到的cell
是td
,而不是input
-你需要得到td
(cell)的子元素input
(为了安全起见,我使用的是querySelector
;如果input
总是第n个孩子,你可以使用children[n]
(其中n
是0基础))。见下文:
function myFunction() {
document.getElementById("print1").innerHTML = document.getElementById("myTable").rows[0].cells[0].querySelector('input[type="checkbox"]').checked;
}
<!DOCTYPE html>
<html>
<head>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Trying to obtain values from checkboxes within a table.</p>
<table id="myTable">
<tr>
<td id='C1'> <input type='checkbox' checked='checked'> </td>
<td id='C2'> <input type='checkbox' checked='checked'> </td>
</tr>
<tr>
<td id='C3'> <input type='checkbox' checked='checked'> </td>
<td id='C4'> <input type='checkbox' checked='checked'> </td>
</tr>
</table>
<p id="print1"></p>
<p id="print2"></p>
<p id="print3"></p>
<p id="print4"></p>
<br>
<button onclick="myFunction()">Try</button>
</body>
</html>