为了账号安全,请及时绑定邮箱和手机立即绑定

如何在用户单击复选框所在的行时切换复选框?

如何在用户单击复选框所在的行时切换复选框?

阿波罗的战车 2022-10-21 17:26:17
我有一个有 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');    }  });});我应该如何修改我的代码以使切换功能起作用?
查看完整描述

2 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

你可以这样做...


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>


查看完整回答
反对 回复 2022-10-21
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

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

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


查看完整回答
反对 回复 2022-10-21
  • 2 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号