【问题标题】:How to bind to javascript events after the DOM changesDOM更改后如何绑定到javascript事件
【发布时间】:2010-05-04 03:17:23
【问题描述】:

我有一个绑定到 tr 标签的函数来提供像这样的鼠标悬停效果:

$(".grid tr").bind("mouseenter", 功能 () { $(this).addClass("hover"); }).bind("mouseleave", function () { $(this).removeClass("hover"); });

问题是发生分页或过滤等时通过 ajax 加载网格。这会导致网格被完全替换并且所有事件绑定都失败。有没有办法绑定到一个事件,即使 DOM 发生变化,它也会自动附加到匹配的元素?

谢谢!

【问题讨论】:

    标签: javascript jquery effects


    【解决方案1】:

    $.live 是你想要的:

    $(".grid tr").live("mouseenter", function () { $(this).addClass("hover"); }).bind("mouseleave", function () { $(this).removeClass("hover"); });
    

    【讨论】:

    • 虽然 live() 可以解决问题,但效率很低。最好钩入ajax调用的成功事件,用新事件更新适用的dom节点
    【解决方案2】:

    请从现在开始使用.on(),因为.live() 在jQuery 中已被弃用,因为它效率低下。

    $(".grid tr")
        .on("mouseenter", function () { $(this).addClass("hover"); })
        .on("mouseleave", function () { $(this).removeClass("hover"); });
    

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 2023-03-27
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      相关资源
      最近更新 更多