0

我需要从不唯一的矩阵单元中获取值。这个模型是原始模型的简化,原始模型是一个巨大的矩阵,这就是为什么我把 enfasis 放在这个模型上:document.getElementById("myTable").rows[0].cells[0]。XXXXXX _

目标:我应该在该指令中使用什么属性或方法来获取复选框(真/假)或(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>
4

1 回答 1

0

复选框的选中/未选中状态存储在其checked属性中。请注意,cell您得到的是 a td,而不是input- 您需要获取td's (单元格的)子元素,它是一个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>

于 2018-09-10T01:18:28.963 回答