jquery - 更改已加载页面中的 jQuery 单击处理程序 anchor

标签 jquery

我有一个母版页,它根据单击的链接将内容加载到 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/

相关文章:

javascript - 如何检查对象是否是 jQuery Xhr 对象

javascript - 进行验证时的 jQuery 问题

javascript - 如何解决点击事件被触发两次的问题?

javascript - 在Javascript : Load some collection of data,中随机排序,返回输出

javascript - 如何在 Bootstrap Modal Box 中显示图片预览?

javascript - 根据输入值更改 div 内容

javascript - 限制容器内可放置拖动项目的数量

javascript - 当我双击将在单击时隐藏的特定元素时,双击绑定(bind)到父元素或同级元素

jquery - 水平/垂直跨浏览器居中图像

jquery - 如何在鼠标悬停事件上更改单元格间距空白?