使用 jQuery.append 时绑定事件会丢失

发布于 2024-11-01 20:48:12 字数 494 浏览 9 评论 0原文

我有一个像这样的简单代码 http://jsfiddle.net/9braK/2/

$(function(){

$('body').append(
    $("<a/>").attr({ "id": "foo", "href":"#" })
             .text("click me")
             .live("click",function(e){
                e.preventDefault();
                alert("Hello World!");
             })
  );
});

根据docs 这应该有效,对吧?

I have a simple code like this http://jsfiddle.net/9braK/2/

$(function(){

$('body').append(
    $("<a/>").attr({ "id": "foo", "href":"#" })
             .text("click me")
             .live("click",function(e){
                e.preventDefault();
                alert("Hello World!");
             })
  );
});

According to the docs this should work, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隔纱相望 2024-11-08 20:48:12

DOM遍历方法不是
支持查找要发送的元素
到.live()。相反,.live() 方法
应该总是在之后直接调用
选择器,如上例所示。

来源

所以代码中唯一的问题是 live() 的使用。 "" 不是选择器,并且 live() 的工作方式将无法找到相应的元素。如果您只是使用 .click(),它当然可以完美地工作。

您可以使用类似的方法

$('body')
  .append(
    $("<a/>")
      .attr({ "id": "foo", "href":"#" })
      .text("click me")
    )
  )
  .delegate("#foo", "click", function(e){
                e.preventDefault();
                alert("Hello World!");
             });

来实现您想要的(但我认为根据您的用例,简单的 click() 就足够了)。

DOM traversal methods are not
supported for finding elements to send
to .live(). Rather, the .live() method
should always be called directly after
a selector, as in the example above.

Source

So the only problem in your code is the usage of live(). "<a/>" is not a selector, and the way live() works it won't be able to find corresponding elements. If you simply use .click(), it will work flawlessly of course.

You can use something like

$('body')
  .append(
    $("<a/>")
      .attr({ "id": "foo", "href":"#" })
      .text("click me")
    )
  )
  .delegate("#foo", "click", function(e){
                e.preventDefault();
                alert("Hello World!");
             });

to achieve what you wanted (but I think a simple click() would be sufficient depending on your use case).

南城追梦 2024-11-08 20:48:12

这个有效:

$(function(){
  // Add the click event for all future elements having the id #foo
  $('#foo').live("click",function(e){
                    e.preventDefault();
                    alert("Hello World!");
                 });

    $('body').append(
        $("<a/>").attr({ "id": "foo", "href":"#" })
                 .text("Continue ")
    );
});

This one works :

$(function(){
  // Add the click event for all future elements having the id #foo
  $('#foo').live("click",function(e){
                    e.preventDefault();
                    alert("Hello World!");
                 });

    $('body').append(
        $("<a/>").attr({ "id": "foo", "href":"#" })
                 .text("Continue ")
    );
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文