我正在寻找以下问题的解决方案:
1) 我正在加载几行文本,其中一些包含指向脚注的链接,如下所示:1)。这些行嵌入在 元素中(见下文)
2)当用户点击这样一行时,相应的脚注文本应该显示几秒钟
3) 在静态上下文中,完成此行为没有问题。然而,我的问题是,1) 下加载的行因调用而异,连接的脚注文本也是如此。因此,我试图找到一种方法将(不同数量的)javascript 事件处理函数动态连接到其相应的脚注文本。
到目前为止,我已经设法编写了以下代码 - 但是它并不能按预期工作:
function displayData(data) {
$('#statisticTable').html(data); // coming from a datapage.php
for (i = 0; i < 15; i++) { // max. 15 footnotes per page
// The lines containing a hint are looking as follows:
// <a href="" id="nt1" class="ui-link">Any Title <sup>1)</sup></a>
$('#nt' + i).click(function() {
if (!notesAlreadyLoaded) {
$.get('notes.php', 'some params', processNotes);
// a footnote looks like this:
// <div class="reg_footnote" id="note1">Comment on Any Title: ... </div>
notesAlreadyLoaded = true;
}
else
// Where can I get the number 'note_index' from?
// Trying to read the 'id' attribute from the <a> element doesn't work?
$("#note"+note_index).fadeIn(800).delay(3000).fadeOut(800);
});
}
$.mobile.changePage('#data');
}
function processNotes(notes) {
$('#footnotes').html(notes);
// where can I get the number 'note_index' from?
$("#note"+note_index).fadeIn(800).delay(3000).fadeOut(800);
}
显然,事件处理函数已正确创建,并且它们也会在正确的时刻被调用。但是,我找不到一种方法来告诉他们应该淡入哪个脚注。
最佳答案
使用事件委托(delegate)。不要将事件绑定(bind)到元素本身,而是绑定(bind)到永远不会被删除或替换的祖先元素上:
<ul id="mylist">
<li><a href="#" class="foo">Foolink</a></li>
</ul>
在上面的代码中,我们可以直接绑定(bind)到 anchor :
$(".foo").on("click", doSomething);
但正如您所指出的,这对于稍后可能放入 DOM 的新链接不起作用。因此,我们应该将工作委托(delegate)给父元素:
$("#mylist").on("click", ".foo", doSomething);
现在该事件已绑定(bind)到祖先元素,这使我们可以响应其中发生的任何 anchor 单击。
当来自与我们的 .foo
选择器匹配的项目的点击事件冒泡到 #mylist
元素时,我们的 doSomething
函数将被触发。
关于jquery - 如何告诉事件处理程序指向动态加载的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567559/