麻烦事件冒泡和JavaScript复选框

时间:2017-08-02 01:28:36

标签: javascript

我尝试在最左边的列中创建一个带有复选框的HTML表格。我希望能够通过单击<tr>元素上的任意位置来选中复选框。我已经让它工作了,但是当我点击复选框本身时它并没有改变状态。我已经在Firefox 54中对此进行了测试(我并不关心其他浏览器)。

我做了一个JSFiddle来证明我的问题https://jsfiddle.net/a92to0tu/

&#13;
&#13;
let table = document.querySelector("table");
table.addEventListener("click", function(e) {
  e.preventDefault();
  let tr = e.target.closest("tr");
  let checkbox = tr.firstElementChild.firstElementChild;
  
  // This doesn't work
  checkbox.checked = !checkbox.checked
  
  // This works but I don't like it
  // setTimeout(function() {
  //   checkbox.checked = !checkbox.checked
  // }, 100);
});
&#13;
<table>
  <tr>
 <td><input type="checkbox"></td>
<td>Click works here too</td>
  </tr>
  <tr>
<td><input type="checkbox"></td>
<td>Click works here too</td>
  </tr>
</table>

<p>I can click the text/table row, but clicking the checkbox no longer works</p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

使用标签元素,您根本不需要任何脚本。

&#13;
&#13;
table {border-collapse: collapse;}
td { border: 1px solid #999999;}
&#13;
<table>
  <tr><td><input type="checkbox" id="foo" name="foo">
      <td><label for="foo">Works here too!</label>
      <td><label for="foo">Works here three!</label>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要设置条件以确保点击不是针对复选框:

if(e.target !== checkbox) {

let table = document.querySelector("table");
table.addEventListener("click", function(e) {
  let tr = e.target.closest("tr");
  let checkbox = tr.firstElementChild.firstElementChild;
  
  if (e.target !== checkbox) {
checkbox.checked = !checkbox.checked
  }
});
<table>
  <tr>
 <td><input type="checkbox"></td>
<td>Click works here too</td>
  </tr>
  <tr>
<td><input type="checkbox"></td>
<td>Click works here too</td>
  </tr>
</table>

<p>I can click the text/table row, but clicking the checkbox no longer works</p>