可点击的行仅适用于数据表的第一页 [英] Clickable row only works on the first page in datatable

查看:118
本文介绍了可点击的行仅适用于数据表的第一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助.我有一个页面,显示引导数据表中的记录.记录每页显示10行,每行的左列都有一个复选框.我想做的是,当用户单击该行时,它将选中该复选框并启用放置在表格后面的按钮(用户必须至少选择一个复选框来激活/启用该按钮).我已经实现了此功能,但不幸的是,它仅在首页上有效.当用户转到第二页并单击表格行时,未选中该复选框.有人可以帮助我吗?非常感谢.

I need help. I have a page that displays records in bootstrap data table. The records are displayed 10 rows per page and each row has a checkbox on the left column. What I want to do is, when user clicks on the row, it will check the checkbox and enable the button placed after the table(user has to select at least a checkbox to activate/enable the button). I already implemented this but unfortunately it only works on the first page. When user go to second page and click on the table row, the checkbox is not checked. Anyone can help me? I appreciate it much.

//disable button when no records are selected
var checkboxes = $("input[type='checkbox']");
var btn = $("#button");
btn.attr("disabled","disabled");

checkboxes.on('click', function(event) {
    if($(this).prop('checked')){
        btn.removeAttr('disabled');
    } else {
        btn.attr("disabled",!checkboxes.is(":checked"));
    }
});

//this will check the checkbox whenever user clicks the table row
$('.clickable-row').click(function (event) {
    if (event.target.type !== 'checkbox') {
        $(':checkbox', this).trigger('click');
    }
}); 

推荐答案

当您将DataTables与jQuery一起使用时,该插件通过在切换页面时从DOM中添加和删除元素来管理页面上显示的行.加载表格后,DOM中唯一存在的行就是该第一页上出现的行.

When you use DataTables with jQuery, the plugin manages the rows that appear on the page by adding and removing elements from the DOM when you switch pages. When the table loads, the only rows that exist in the DOM are those appearing on that first page.

这意味着您的处理程序只会添加到第一页的元素中,并且在切换页面后,这些元素将被删除,因此当您返回到第1页时,这些将是新创建的没有附加处理程序的元素.

This means that your handler is only ever added to the first page's elements and once you switch pages, those elements are removed so when you go back to page 1, those will be newly created elements with no handlers attached.

将代码更改为此:

$('#some-table-id').on('click','.clickable-row', function (event) {
    if (event.target.type !== 'checkbox') {
        $(':checkbox', this).trigger('click');
    }
}); 

这称为事件委托

另请参见在动态创建的元素上进行事件绑定?

这篇关于可点击的行仅适用于数据表的第一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆