javascript - 追加元素后刷新 DOM

标签 javascript jquery

<!doctype html>
<html>

<head>
  <title>test</title>
  <meta charset="UTF-8">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#main_body').append("<h1>Hello</h1><input id=\"but\" type=\"button\">Click");
      $("#but").on("click", function() {
        alert("bla bla");
      });
    });
  </script>
</head>

<body id="main_body"></body>

</html>

为什么追加 DOM 后警报不起作用?点击后应该显示“bla bla”。

已解决

主要问题是:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

我认为 jquery 太旧了

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

问题已解决:)

最佳答案

对于动态添加的元素,您需要事件委托(delegate),请使用 jQuery 上的其他版本 on() ,您可以将事件委托(delegate)给动态添加元素的静态父级。在您的情况下,您可以使用 #main_body

$('#main_body').on( "click", "#but", function() {
    alert( "bla bla" );
});    

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery Docs

您的代码有效 here这是因为您在绑定(bind)事件之前添加动态元素,但使用事件委托(delegate)将使您摆脱用于添加动态元素的顺序。

关于javascript - 追加元素后刷新 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22373630/

相关文章:

javascript - event.target 被弃用了吗?

javascript - Foundation 4 和 backbone.js 的等高柱

javascript - 多次触发粘贴事件

jquery - Colorfinder.js 错误

javascript - 使用 jQuery 将实例从 View 传递到 Controller

javascript - 使用AJAX读取本地文件

javascript - 在 Angular2 中的 service 中注入(inject)服务

javascript - 我无法通过 TestCafe 获得预期的 URL

javascript - if 之外 && 的奇怪用法?

javascript - 单击 Codeigniter 中的“编辑”按钮时更新 Bootstrap 表