单击表行上的任何位置,它将选中它的复选框

click anywhere on a table row and it will check the checkbox its in...?

本文关键字:复选框 位置 任何 单击      更新时间:2023-09-26

我想知道如何做到这一点,但我找不到它。基本上,我希望能够在任何地方单击表行,它将检查/未检查复选框其在。我知道这是可能的,因为这是PHPMyAdmin做的…

这是我的表行

<tbody>
<tr id="1" onclick="selectRow(1)"><td width="20px"><input type="checkbox" id="1" name="1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr id="2" onclick="selectRow(2)"><td width="20px"><input type="checkbox" id="2" name="2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
<script type="text/javascript">
function selectRow(row)
{
    var firstInput = row.getElementsByTagName('input')[0];
    firstInput.checked = !firstInput.checked;
}
</script>

<tbody>
    <tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk1" name="chk1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>    
    <tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>  
</tbody>

注意:id上也有碰撞。您的id必须是唯一的

这里有一个可选择的编程绑定:

document.querySelector("table").addEventListener("click", ({target}) => {
  // discard direct clicks on input elements
  if (target.nodeName === "INPUT") return;
  // get the nearest tr
  const tr = target.closest("tr");
  if (tr) {
    // if it exists, get the first checkbox
    const checkbox = tr.querySelector("input[type='checkbox']");
    if (checkbox) {
      // if it exists, toggle the checked property
      checkbox.checked = !checkbox.checked;
    }
  }
});
<table>
  <tbody>
    <tr>
      <td>
        <input type="checkbox" id="chk1" name="chk1" />
      </td>
      <td>1</td>
      <td>2011-04-21 22:04:56</td>
      <td>action</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" id="chk2" name="chk2" />
      </td>
      <td>2</td>
      <td>2011-04-21 22:04:56</td>
      <td>action</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" id="chk2" name="chk3" />
      </td>
      <td>2</td>
      <td>2011-04-21 25:30:16</td>
      <td>action</td>
    </tr>
  </tbody>
</table>

你不需要JavaScript:

td label {
  display: block;
}
<td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td><label for="chk2">2</label></td><td><label for="chk2">2011-04-21 22:04:56</label></td><td><label for="chk2">action</label></td>

只是标签和一些CSS。

试试这个…

$("tr").click(function() {
    var checkbox = $(this).find("input[type='checkbox']");
    checkbox.attr('checked', !checkbox.attr('checked'));
});
http://jsfiddle.net/dVay8/

既然这个问题有这么多的观点和公认的答案有一个小问题。

问题是当你点击复选框时,它不会改变。实际上发生的是复选框切换两次。因为我们点击了复选框和表格行。所以这里有一个适当的解决方案与修复。

$('tr').click(function(event){
    var $target = $(event.target);
    if(!$target.is('input:checkbox'))
    {
        $(this).find('input:checkbox').each(function() {
            if(this.checked) this.checked = false;
            else this.checked = true;
        })
    }
});