我正在使用带有隐藏行的 DataTables 插件,当使用分页时,我的点击事件失败,没有控制台错误。
这是函数:
$(document).ready(function() {
$('#datatable tbody td a').on('click', function (e) {
e.preventDefault();
var nTr = $(this).parents('tr')[0];
if ( oTable.fnIsOpen(nTr) ) {
/* This row is already open - close it */
$(this).addClass('glyphicon-arrow-down');
$(this).removeClass('glyphicon-arrow-up');
oTable.fnClose( nTr );
} else {
/* Open this row */
$(this).addClass('glyphicon-arrow-up');
$(this).removeClass('glyphicon-arrow-down');
oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
}
});
});
正如您所看到的,我正在使用委托(delegate),但该函数被包装在一个准备好的函数中。我确信这就是问题所在。我该如何解决这个问题?
上述问题是错误提出的,请参阅答案下我的评论。
最佳答案
阅读.on()
由于元素是动态添加的,因此您无法将事件直接绑定(bind)到它们。因此您必须使用 Event Delegation .
$('#datatable').on('click', 'tbody td a', function (e) {});
语法
$( elements ).on( events, selector, data, handler );
下面的代码不是事件委托(delegate)
$('#datatable tbody td a').on('click', function (e) {
关于javascript - 就绪函数内的委托(delegate)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19609085/