亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在用戶單擊復選框所在的行時切換復選框?

如何在用戶單擊復選框所在的行時切換復選框?

阿波羅的戰車 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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號