javascript 分页后无法调用 onclick 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8661501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Datatables I can't call an onclick event after I paginate?
提问by Tallboy
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>
<a href="#" class="show-post"><%= Post.title %></a>
This link opens a jquery UI modal dialog which displays some information which is ajax requested.
此链接将打开一个 jquery UI 模式对话框,该对话框显示一些 ajax 请求的信息。
Part 1 (solved), see part 2 below
第 1 部分(已解决),请参阅下面的第 2 部分
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)
我正在尝试运行一个在第一页上正常工作的 onclick 事件,但是一旦我转到第 2 页(或任何其他页面),它就会停止工作。我检查了源代码以确保它在所有代码中都没有做任何有趣的事情(所有行,甚至是分页隐藏的行)
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
第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.
我想开始工作的下一个“问题”ID 是...我使用左右箭头键让他们“扫描”到下一行或上一行,并显示信息。这与关闭它然后必须单击下一个相反。
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)
这是我的点击功能(我知道它的结构可能不是最好的......我是 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;
};
回答by Jasper
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?
您提供的链接上的示例似乎是添加/删除 DOM 元素,这意味着后续页面上的元素在页面加载时可能不在 DOM 中。您是否尝试过使用事件委托?
$(<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.
Where<root element>
可以document
但应该设置为始终在 DOM 中的祖先元素。
.delegate()
:
.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
来源: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() { ... });
请注意,这.delegate()
是.on()
现在的别名,因此如果您使用的是 jQuery 1.7+,我会.on()
从一开始就使用。除了选择器和事件交换之外,几乎相同的语法:$(<root element>).on('click', '.show-post', function() { ... });
Source: Thanks Greg Pettit, Excellent Comment
资料来源:感谢 Greg Pettit,优秀评论
回答by Kavivarman
Below Code is working Perfectly. When you click the pagination button 'drawCallback' class Call some function after table load.
下面的代码工作正常。当您单击分页按钮时 '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']], });
回答by Matt K
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:
正如@scrappedcola 在评论中指出的那样,您的点击处理程序在分页后丢失。drawCallback
您可以实现一个DataTables 函数,该函数将在“重新绘制”表格后触发(因此是 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
});
}
});