【问题标题】:How to toggle the checkbox while the user clicks on the row where the checkbox resides in?当用户单击复选框所在的行时,如何切换复选框?
【发布时间】:2020-06-29 14:05:05
【问题描述】:

我有一个有 2 列的表格,第一列显示文本,另一列有一个复选框。

代码如下,复选框JavaScript生成,例如var checkbox = document.createElement("input");

<script type="text/javascript">
      function create_table() {
       var data = ["Sandwidch", "Hamburger", "Bacon"];
       var table = document.getElementById("menu");
       for (var option in data) {
          var row = table.insertRow(-1);
          var cell1 = row.insertCell(0);
          cell1.innerHTML = data[option];

          var cell2 = row.insertCell(1);
          var checkbox = document.createElement("input");
          checkbox.type = "checkbox";
          checkbox.name = "choiceCbx";
          cell2.appendChild(checkbox);
        }
      }
      window.onload = create_table;
</script>

<body>
    <table id="menu">
        <tr>
           <th>Food</th>
           <th>Choice</th>
        </tr>
    </table>
</body>

当用户点击表格中的某一行时,如果该行上的复选框被选中,它应该变为未选中,反之亦然。

我使用以下代码来切换复选框,但徒劳无功,它似乎只检测到“TH”行,而不是“TR”行:

$(document).ready(function() {
  $('#menu tr').click(function(event) {
    if (event.target.type !== 'checkbox') {
      $(':checkbox', this).trigger('click');
    }
  });
});

我应该如何修改我的代码以使切换功能起作用?

【问题讨论】:

  • 你不喜欢我的回答?你测试了吗?
  • 它有效,谢谢。

标签: javascript jquery dom


【解决方案1】:

你可以这样做......

const table_foods = document.querySelector('#records tbody')

table_foods.onclick=e=>
  {
  if (e.target.matches('input[type=checkbox]')) return  // to not disturb  natural check action
  let chkBx = e.target.closest('tr').querySelector('input[type=checkbox]')
  chkBx.checked = !chkBx.checked  
  }
 /* cosmetic part */

table {
  border-collapse: collapse;
  margin-top: 25px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  } 
thead {
  background-color: aquamarine;
  }
tbody {
  background-color: #b4c5d8;
}
td, th {
  border: 1px solid grey;
  padding: .3em .7em;
}
<table id="records" class="content">
  <thead>
    <tr> <th>Food</th> <th>Choice</th> </tr>
  </thead>
  <tbody>
    <tr>
      <td>Sandwitch</td>
      <td><input type="checkbox" name="answerCbx-1" /></td>
    </tr>
    <tr>
      <td>pizza</td>
      <td><input type="checkbox" name="answerCbx-2" /></td>
    </tr>
  </tbody>
</table>

【讨论】:

    【解决方案2】:

    试试这个。此外,您可能想为您的问题添加更多详细信息,因为 HTML 不包含任何复选框

    https://forum.jquery.com/topic/toggle-checkboxes-in-a-table-after-click-function

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多