由于我之前没有发现任何问题,关于如何在单击表格行时切换复选框,所以我想分享我对此的方法......
5 回答
为了选择表格中一行的复选框,我们将首先检查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
}
});
这个问题对我很有用,但我对以前的解决方案有疑问。如果您单击表格单元格中的链接,它将触发复选框切换。我用谷歌搜索了这个,我看到了一个在表格的链接上添加 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');
}
});
您可能希望更具体地了解测试条件,例如,如果您在行中有其他输入。
像上面提供的许多解决方案一样触发点击将导致函数运行两次。改为更新 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);
}
});
即使接受了@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 事件
您可以简单地触发此点击事件... :)
$(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');
});
});