将点击绑定到 panzoom 容器中的元素
bind click to an element within panzoom container
我正在使用 jquery.panzoom 来包含一个 table。
每个 table 单元格都是这种形式:
<td><div class="cell" id="cell-24-14"></div></td>
table 是动态创建的,所以我用它来尝试捕获一个事件:
$('.cell').on('click', function (e) {
alert($(this).attr('id'));
});
我试过删除 divs,并直接捕捉 td 上的点击,但这并没有奏效。
当我捕捉到任何 div 上的点击时,我看到 table 的容器捕捉到了点击,但点击永远不会到达 table 本身(而不是它的单元格) ).
如何在 td(甚至 td)内的 individual div 上捕获点击事件?
您实际上可以将事件绑定移动到将这些元素添加到 DOM 的函数中,就像这样
function appendToDOM(){
// creating a td element and appending to DOM
var td = $('<td><div class="cell" id="cell-24-14"></div></td>');
td.appendTo($table);
/* now that the element is available in DOM, you can define you event handler here*/
$('.cell').on('click', function (e) {
alert($(this).attr('id'));
});
}
这种方法的问题是您要为 table 中的每个 .cell
元素定义一个事件处理程序,您可以通过使用委派做得更好。
$('urClosestStaticParent').on('click','.cell',function(e){
alert($(this).attr('id'));
});
您可以在显示 table 之前调用此代码,作为画龙点睛之笔:)
当我说最近的静态父级时,我指的是您正在创建的动态 table 的父级,可能是来自文档加载的 div 容器。如果你没有任何这样的元素,你可以尝试在你的 html 中添加一些空 div,将你的 table 附加到它并使用它,如果不使用 document
相反。
我正在使用 jquery.panzoom 来包含一个 table。
每个 table 单元格都是这种形式:
<td><div class="cell" id="cell-24-14"></div></td>
table 是动态创建的,所以我用它来尝试捕获一个事件:
$('.cell').on('click', function (e) {
alert($(this).attr('id'));
});
我试过删除 divs,并直接捕捉 td 上的点击,但这并没有奏效。
当我捕捉到任何 div 上的点击时,我看到 table 的容器捕捉到了点击,但点击永远不会到达 table 本身(而不是它的单元格) ).
如何在 td(甚至 td)内的 individual div 上捕获点击事件?
您实际上可以将事件绑定移动到将这些元素添加到 DOM 的函数中,就像这样
function appendToDOM(){
// creating a td element and appending to DOM
var td = $('<td><div class="cell" id="cell-24-14"></div></td>');
td.appendTo($table);
/* now that the element is available in DOM, you can define you event handler here*/
$('.cell').on('click', function (e) {
alert($(this).attr('id'));
});
}
这种方法的问题是您要为 table 中的每个 .cell
元素定义一个事件处理程序,您可以通过使用委派做得更好。
$('urClosestStaticParent').on('click','.cell',function(e){
alert($(this).attr('id'));
});
您可以在显示 table 之前调用此代码,作为画龙点睛之笔:)
当我说最近的静态父级时,我指的是您正在创建的动态 table 的父级,可能是来自文档加载的 div 容器。如果你没有任何这样的元素,你可以尝试在你的 html 中添加一些空 div,将你的 table 附加到它并使用它,如果不使用 document
相反。