数据表分页后无法调用 onclick 事件?

发布于 2024-12-23 17:18:32 字数 3819 浏览 0 评论 0原文

我正在使用 http://datatables.net/

他们主页上的演示表与我正在使用的几乎完全相同(分页)具体而言),但每行都有一个可点击的区域:

<%= Post.title %>

此链接打开一个 jquery UI 模式对话框它显示 ajax 请求的一些信息。

第 1 部分(已解决),请参阅下面的第 2 部分

我正在尝试运行一个 onclick 事件,该事件在第一页上正常工作,但是一旦我转到第二页(或任何其他页面),它就会停止工作。我检查了源代码,以确保它没有做任何有趣的事情,所有代码实际上都在那里(所有行,甚至是分页隐藏的行)

有什么想法吗?

$(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 部分

我想要开始工作的下一个“问题”ID 是...我使用左右箭头键允许它们“扫描”到下一行或上一行,并显示的信息。这与关闭它然后必须单击下一个相反。

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

这是我的点击函数(我知道它的结构可能不是最好的......我是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;
};

I am using http://datatables.net/

The demo table on their homepage resembles pretty much the exact same thing that i'm using (pagination, specifically), except each row has an area to click:

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

This link opens a jquery UI modal dialog which displays some information which is ajax requested.

Part 1 (solved), see part 2 below

I'm trying to run an onclick event which works normally on page one, but as soon as i go to page 2 (or any others) it stops working. I checked the source to make sure it wasnt doing anything funny in all the code is infact there (all the rows, even the ones hidden by the pagination)

Any ideas?

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

Thanks to those who answered my question! I fixed that issue.

Part 2

my next 'issue' id like to get to work is... I'm using the left and right arrow keys to allow them to 'scan' to the next or previous row, and display the information. This is as opposed to closing it and then having to click the next one.

I'd like to make it so when you get to the bottom of page one, or top of page two, hidding next/previous respectively will automatically load that page, go to the top (or bottom), then open that dialog for that row on the other page.

heres my click function (i know its kind of probably not structured the best... im new to 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)
        }
    });
});

heres the actual click function

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;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江南月 2024-12-30 17:18:32

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

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

其中 可以是 document 但应设置为始终位于 DOM 中的祖先元素。

.delegate()

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

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

更新

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

来源:谢谢 Greg Pettit,非常好的评论

The example on the link you provided appears to be adding/removing DOM elements, meaning that elements on subsequent pages probably are not in the DOM on page load. Have you tried using event delegation?

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

Where <root element> can be document but should be set to an ancestor element that is always in the DOM.

.delegate():

Attach a handler to one or more events for all elements that match the
selector, now or in the future, based on a specific set of root
elements.

Source: http://api.jquery.com/delegate

UPDATE

Note that .delegate() is an alias of .on() now, so if you're using jQuery 1.7+ I would just use .on() right from the get-go. Almost the same syntax except the selector and event are swapped: $(<root element>).on('click', '.show-post', function() { ... });

Source: Thanks Greg Pettit, Excellent Comment

蹲在坟头点根烟 2024-12-30 17:18:32

下面的代码运行完美。当您单击分页按钮“drawCallback”类时,在表加载后调用一些函数。

$("#YourTableID").dataTable({
                    bJQueryUI: false,
                    bFilter: false,
                    bSearchable: false,
                    bInfo: false,
                    bAutoWidth: false,
                    bDestroy: true,
                    "oLanguage": {
                        "sEmptyTable": "No Records Found"
                    },
                    "sPaginationType": "full_numbers",
                    "bLengthChange": false,
                    "iDisplayLength": 5,
                    aaData: arrv,
                    aoColumns: [{
                        sTitle: "Select",
                        orderable: false,
                        className: 'select-checkbox',
                        targets: 0
                    },
                    {
                        sTitle: "Course name"
                    }, {
                        sTitle: "Level"
                    }, {
                        sTitle: "Study Mode"
                    }, {
                        sTitle: "Entry Year"
                    }, {
                        sTitle: "Point of Entry"
                    }, {
                        sTitle: "Awarding qualification"
                    }],
                    drawCallback: function () {
                        //Some function...
                    },
                    select: {
                        style: 'os',
                        background: 'color:gray',
                        selector: 'td:first-child'
                    },
                    order: [[1, 'asc']],

                });

Below Code is working Perfectly. When you click the pagination button 'drawCallback' class Call some function after table load.

$("#YourTableID").dataTable({
                    bJQueryUI: false,
                    bFilter: false,
                    bSearchable: false,
                    bInfo: false,
                    bAutoWidth: false,
                    bDestroy: true,
                    "oLanguage": {
                        "sEmptyTable": "No Records Found"
                    },
                    "sPaginationType": "full_numbers",
                    "bLengthChange": false,
                    "iDisplayLength": 5,
                    aaData: arrv,
                    aoColumns: [{
                        sTitle: "Select",
                        orderable: false,
                        className: 'select-checkbox',
                        targets: 0
                    },
                    {
                        sTitle: "Course name"
                    }, {
                        sTitle: "Level"
                    }, {
                        sTitle: "Study Mode"
                    }, {
                        sTitle: "Entry Year"
                    }, {
                        sTitle: "Point of Entry"
                    }, {
                        sTitle: "Awarding qualification"
                    }],
                    drawCallback: function () {
                        //Some function...
                    },
                    select: {
                        style: 'os',
                        background: 'color:gray',
                        selector: 'td:first-child'
                    },
                    order: [[1, 'asc']],

                });
酒解孤独 2024-12-30 17:18:32

正如 @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
        });
    }
});

As @scrappedcola pointed out in the comments, your click handler is lost after pagination. There is a drawCallback function for DataTables you can implement which will fire after the table is "re-drawn" (hence drawCallback). Here is an example:

$('#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
        });
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文