我有一个母版页,它根据单击的链接将内容加载到 div 中。我通过使用 jQuery 为某些 anchor 添加点击处理程序来实现此目的:
<div id="nav">
<a href="somepage.html">
...
</div>
<div id="content"/>
<script type="text/javascript">
$(document).ready(function() {
$('#nav a, #footer a').click(function(e) {
$('#content').load($(this).attr('href'));
return false;
});
});
</script>
加载到 #content 中的一些页面也有我想为其添加点击处理程序的 anchor (因此这些点击的结果也会进入 #content 中)。我试过这个:
$('#content a').click(function(e) {
...
});
但这似乎不起作用。有什么想法可以在这些加载的页面中的 anchor 上设置点击处理程序吗?
最佳答案
$(document).on('click', '#content a', function(e) {
...
});
应该可以。当您动态添加元素时,您需要使用 on()
将它们绑定(bind)到事件。来自文档:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
理想情况下,您希望 DOM 中的父元素比 document
更近。
关于jquery - 更改已加载页面中的 jQuery 单击处理程序 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13092877/