28

由于我之前没有发现任何问题,关于如何在单击表格行时切换复选框,所以我想分享我对此的方法......

4

5 回答 5

88

为了选择表格中一行的复选框,我们将首先检查type attribute我们所定位的元素是否不是复选框,如果它不是复选框,那么我们将检查嵌套在该表格行中的所有复选框。

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

演示


如果您想突出显示表格行,checkbox checked我们可以使用if条件 with is(":checked"),如果是,则我们tr使用 and 找到最接近的元素.closest(),然后使用addClass()

$("input[type='checkbox']").change(function (e) {
    if ($(this).is(":checked")) { //If the checkbox is checked
        $(this).closest('tr').addClass("highlight_row"); 
        //Add class on checkbox checked
    } else {
        $(this).closest('tr').removeClass("highlight_row");
        //Remove class on checkbox uncheck
    }
});

演示

于 2013-08-18T07:46:01.093 回答
7

这个问题对我很有用,但我对以前的解决方案有疑问。如果您单击表格单元格中的链接,它将触发复选框切换。我用谷歌搜索了这个,我看到了一个在表格的链接上添加 a 的提议event.stopPropagation(),如下所示:

$('.record_table tr a').click(function(event) {
  event.stopPropagation();
});

这个解决方案是个坏主意,因为我在表的链接上有一些 jquery bootstrap popover ......

所以这里有一个更适合我的解决方案。顺便说一句,当我使用 bootstrap 2.3 时,该行的亮点是通过将“info”类添加到 tr。要使用此代码,您只需添加class="selectable"到 table 标记。

$(".selectable tbody tr input[type=checkbox]").change(function(e){
  if (e.target.checked)
    $(this).closest("tr").addClass("info");
  else
    $(this).closest("tr").removeClass("info");
});

$(".selectable tbody tr").click(function(e){
  if (e.target.type != 'checkbox' && e.target.tagName != 'A'){
    var cb = $(this).find("input[type=checkbox]");
    cb.trigger('click');
  }
});

您可能希望更具体地了解测试条件,例如,如果您在行中有其他输入。

于 2014-01-19T21:17:18.110 回答
5

像上面提供的许多解决方案一样触发点击将导致函数运行两次。改为更新 prop 值:

$('tr').click(function(event){
  alert('function runs twice');
  if(event.target.type !== 'checkbox'){
    //$(':checkbox', this).trigger('click');
    // Change property instead
    $(':checkbox', this).prop('checked', true);
  }
});

此处链接到 jsfiddle 示例

于 2016-08-01T18:58:28.280 回答
1

即使接受了@Mr。<tr>Alien answer 效果很好,如果您决定在某个时候使用 jQuery 动态添加新行,它就不起作用。

我建议使用事件委托方法,这只是对已接受答案的轻微修改。

代替:

... $('.record_table tr').click(function(event) { ...

利用

... $('.record_table').on('click', 'tr', function(event) { ...

与突出显示相同,使用:

... $(".record_table").on('change', "input[type='checkbox']", function (e) { ...

此处的更多信息:动态添加的表行不会触发 Click 事件

于 2016-09-13T20:44:48.637 回答
0

您可以简单地触发此点击事件... :)

  $(document).ready(function()
    {
      $("table tr th :checkbox").click(function(event)
      {
        $('tbody :checkbox').trigger('click');
      });
    });

或者

  $(document).ready(function()
    {
      $("table tr th :checkbox").on('click',function(event)
      {
        $('tbody :checkbox').trigger('click');
      });
    });
于 2016-01-12T11:32:22.153 回答