jQuery 函数不适用于 AJAX 加载的内容

标签 jquery ajax

我有一个页面index.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Lufia</title>
    <script src="js/jquery.js" language="javascript"></script>
    <script language="javascript">

    $(document).ready(function() {
      $("button").click(function() {
        $('#mydiv').html( 'Loading... ').load('welcome.html');
        $(this).hide();
      });
    });

    </script>
  </head>
  <body>
    <button>ajax</button><div id="mydiv"></div>
  </body>
</html>

在此代码中,当在 midiv 中单击按钮时,加载 welcome.html 并且按钮被隐藏。

welcome.html如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Lufia</title>
  </head>
  <body>
    <button>New Button</button>
  </body>
</html>

这个新按钮的 onClick 不起作用。为什么?

最佳答案

此处的简单解决方案 - 您需要使用 jQuery .live() 函数为新按钮添加事件处理程序。

$("#newButton").live('click',function(){
  // Do stuff here
});

当您最初创建 .click() 处理程序时,第二个 button 尚未在 DOM 中,因此 jQuery 无法向其附加事件处理程序。 .live() 函数适用于 DOM 中已有的任何元素以及将来添加的任何元素(例如,来自 ajax 调用)。

您可能想要为您的新按钮(来自 ajax 调用)提供一个新的不同 ID,因为选择器 $("button") 将捕获您的两个按钮(即使其中一个按钮是隐藏的) .

<小时/>

注意!

自 jQuery 1.7 版起,live() 方法 has been deprecated! 。从版本 1.9 开始,此函数将被完全删除...处理这些动态添加元素的事件处理程序的正确方法现在是使用 on() function.

关于jQuery 函数不适用于 AJAX 加载的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161938/

相关文章:

javascript - 如何使用 javascript 将文本框值转换为 Firefox 和 Internet Explorer 中的日期格式

javascript - 对于简单的 jQuery fadeOut 有一个小问题吗?

javascript - Bootstrap popover 不会第一次出现在使用 ajax 的悬停事件上

Javascript XML 相同元素名称

javascript - 使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如::before 和::after

javascript - 无法在放置的字段之间放置元素

php - 在 PHP 中使用 AJAX 进行图像预览

使用 Codeigniter 和 jQuery 表单插件上传 Ajax 文件

javascript - 在 MVC5 中使用 AJAX 调用

javascript - jQuery 在 while 循环数据中获取来自 AJAX 的属性值