单击表行以使用jQuery选择复选框

由于我之前没有找到任何问题,关于如何在点击表格行时切换复选框,所以我想分享我的方法…

为了选择表中行的复选框,我们将首先检查我们所针对的元素的type attribute是否不是复选框,如果它不是checbox,则检查嵌套在该表行内的所有复选框。

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

演示


如果你想突出显示checkbox上的表格行,我们可以使用带有is(":checked")if条件,如果是,我们使用.closest()找到最接近的tr元素,而不是使用addClass()向它添加类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 } }); 

演示

这个问题对我很有用,但我之前的解决方案存在问题。 如果单击表格单元格中的链接,则会触发复选框切换。 我搜索了这个,我看到了一个命题,在表的链接上添加了一个event.stopPropagation() ,如下所示:

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

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

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

 $(".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'); } }); 

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

像上面提供的许多解决方案一样触发点击将导致该function运行两次。 改为改变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示例

你可能只是触发这个点击事件…… 🙂

  $(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'); }); }); 

即使被接受的@Mr。 Alien的答案效果很好,如果您决定在某些时候使用jQuery动态添加新的

行,它就不起作用。

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

代替:

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

使用

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

并且突出显示相同,使用:

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

更多信息: 对于动态添加的表行,不会触发Click事件