我不能在分页后调用onclick事件

Datatables I can't call an onclick event after I paginate?

本文关键字:调用 onclick 事件 分页 不能      更新时间:2023-09-26

我使用http://datatables.net/

他们主页上的演示表与我使用的几乎完全相同(特别是分页),除了每一行都有一个点击区域:

<a href="#" class="show-post"><%= Post.title %></a>

这个链接打开一个jquery UI模态对话框,其中显示一些ajax请求的信息。

第1部分(已解决),参见下面

第2部分

我试图运行一个在第一页正常工作的onclick事件,但只要我去到第2页(或任何其他)它停止工作。我检查了源代码,以确保它没有做任何有趣的事情,所有的代码都在那里(所有的行,甚至那些隐藏的分页)

任何想法?

$(function() {
    $('#dialog').dialog({
        autoOpen: false,
        resizable: false,
        maxHeight: 600,
        width: 650,
        modal: true,
        beforeClose: function close() {
            $('#dialog').html('');
        }
    });
    $('.show-post').click(function() {
        clickLink(this);
        return false;
    });
});

感谢那些回答我问题的人!我修复了这个问题。

第2部分

我想要开始工作的下一个"问题"是……我使用左右箭头键来允许他们"扫描"到下一行或前一行,并显示信息。这是相对于关闭它,然后不得不点击下一个。

我想这样做,当你到达第一页的底部,或第二页的顶部,隐藏下一个/上一个分别将自动加载该页,到顶部(或底部),然后打开对话框的那一行在另一个页面。

这是我的点击功能(我知道它的结构可能不是最好的…我是jquery新手)
$(document).ready(function() {
    oTable = $('#posts').dataTable({
      "bJQueryUI": true,
      "iDisplayLength": 400,
        "bAutoWidth": false,
        "sPaginationType": "full_numbers",
        "aLengthMenu": [[-1, 400, 100, 50], ["All", 400, 100, 50]]
    });
    $(this).keydown(function(e) {
        var id = $("#dialog").attr("data-id");
        currentPost = $("#posts tr[data-id=" + id + "]");
        if (e.keyCode == 39 && $('#dialog').html() != "") {
            /* Remove current background */
            $(currentPost).blur()
            $(currentPost).removeClass("current");
            $(currentPost).find("td.sorting_1").removeClass("current");
            var next = currentPost.next().find(".show-post");
            clickLink(next);
        } else if (e.keyCode == 37 && $('#dialog').html() != "") {
            /* Remove current background */
            $(currentPost).removeClass("current");
            $(currentPost).find("td.sorting_1").removeClass("current");
            var prev = currentPost.prev().find(".show-post");
            clickLink(prev)
        }
    });
});

这里是实际的点击功能

function clickLink(src) {
var post = $(src);
var id = $(post).parent().parent().attr('data-id');
/* Set background for current line */
$(post).parent().parent().find("td.sorting_1").addClass("current");
$(post).parent().parent().addClass("current");
$('#dialog').attr("data-id", id);
$('#dialog').load('/show-post/' + id, function() {
    $.ajax({
        type: "POST",
        url:  "/checkstatus/" + id,
        dataType: "html",
        error: function(data){
            $("#dialog").fadeOut("fast", function() {
            $("#dialog").html("<img src='/img/invalid.jpg' alt='invalid' style='margin: 40px auto; display: block;'>").fadeIn("slow");
           });
        }
    });
    /* Set Visited */
    $(post).parent().parent().removeClass("visited").addClass("visited");
    $('#dialog').dialog({
        title: post.html(),
        beforeClose: function close() {
            $(post).parent().parent().find("td.sorting_1").removeClass("current");
            $(post).parent().parent().removeClass("current");
        },
        buttons: {
            "Email 1": function() {
                $.ajax({
                    type: "POST",
                    url:  "/get-email/" + id + "/" + "1",
                    dataType: "html",
                    success: function(data) {
                        window.location.href = data + "&subject=" + post.html();
                    }
                });
            },
        }
    });
    $('#dialog').dialog('open');
});
return false;
};

您提供的链接上的示例似乎在添加/删除DOM元素,这意味着后续页面上的元素可能不在页面加载时的DOM中。您尝试过使用事件委托吗?

$(<root element>).delegate('.show-post', 'click', function() {
    clickLink(this);
    return false;
});

其中<root element>可以是document,但应该设置为始终在DOM中的祖先元素。

.delegate():

将处理程序附加到一个或多个事件上,用于匹配的所有元素选择器,现在或将来,基于一组特定的根

元素。

来源:http://api.jquery.com/delegate

注意.delegate()现在是.on()的别名,所以如果你正在使用jQuery 1.7+,我会从一开始就使用.on()。除了选择器和事件交换之外,几乎相同的语法:$(<root element>).on('click', '.show-post', function() { ... });

来源:感谢Greg Pettit,优秀的评论

下面的代码工作完美。当你点击分页按钮'drawCallback'类在表加载后调用一些函数

<>之前$ (" # YourTableID ") .dataTable ({bJQueryUI:假的,bFilter:假的,bSearchable:假的,bInfo:假的,bAutoWidth:假的,bDestroy:没错," oLanguage ": {"sEmptyTable": "No Records Found"},:"sPaginationType full_numbers","bLengthChange":假的,"iDisplayLength":5aaData: arrv,aoColumns: [{sTitle:"选择",公开:定货假,名称:"select-checkbox",目标:0},{标题:"课程名称"}, {sTitle:"水平"}, {标题:"学习模式"}, {标题:"入职年份"}, {标题:"入境点"}, {标题:"授予资格"}),drawCallback:函数(){//函数…},选择:{风格:"操作系统",背景:颜色:灰色,选择器:"道明:第一个孩子"},Order: [[1, 'asc']],});

正如@scrappedcola在评论中指出的那样,您的点击处理程序在分页后丢失。有一个drawCallback函数的数据表,你可以实现它将触发表后"重新绘制"(因此drawCallback)。下面是一个例子:

$('#someId').DataTable({
    lengthMenu: [ 25, 50, 100, 200 ],
    order: [[ 0, 'asc' ]],
    processing: true,
    serverSide: true,
    stateSave: true,
    responsive: true,
    bDestroy: true,
    columns: [
        { data: 'id', name: 'id' },
        { data: 'name', name: 'name' },
    ],
    drawCallback: function() {
        var api = this.api();
        api.$('#someBtnId').click(function() {
            // do some click handler stuff
        });
    }
});