【问题标题】:do I have to detach events from deleted Elements? [duplicate]我必须从已删除的元素中分离事件吗? [复制]
【发布时间】:2013-06-02 06:52:36
【问题描述】:

我正在通过 Ajax 将一些元素加载到 div 并添加一些事件,如下所示:

$('.zoom-container').on('touchmove click scroll mousedown mousewheel', zoom.userEvent) 

我的html:

<div id="Overlay"></div>

我创建一些内容的代码:

$(".full_screen_icon").on({        //delegation
   click: function(evt) {
        var my_html ="zoom  prtty▲thngs";
        var colWidth= $(".block-wrap[data-colspan='2']").eq(0).outerWidth() || "300px";
            //content div erstellen
            $("<div>", {
            id: "detail_content",
                css: {
                    height:colWidth,
                    width:colWidth,
                    "margin-top":-colWidth/2,
                    "margin-left":-colWidth/2
                },
                html: my_html
            })
            .appendTo("#Overlay");

        //content holen via ajax
        $.get("http://www.yxz.de/products/"+ t +".php", function( html ) {
            $("#detail_content").html(html);
        }, 'html');
    }
       .. add zoom-container with some events like above

});

要关闭覆盖,我这样做:

$("#Overlay").click(function (e) {
    $(this).find('#detail_content').empty().remove();       
});

我一直认为,如果我删除带有附加事件的元素,事件也会消失。

但在这里我加载的是单击相同命名的元素并附加相同的命名事件。

我看到删除 div.element 后事件仍然存在。这是我的代码中的问题还是这是正常行为?

我现在很不安全。事件是否随元素一起删除?

【问题讨论】:

  • 您如何看到事件仍然存在?那有什么意思?您可能将事件与事件处理程序混淆了。
  • zoom.userEvent 向元素添加点击事件。如果我删除元素并再次添加,则单击事件是双倍的。
  • 奥马尔:你是对的。我之前没看到过

标签: javascript jquery


【解决方案1】:

如果我理解正确,您需要做的就是创建一个委托侦听器而不是常规侦听器。

$("#Overlay").on('touchmove click scroll mousedown mousewheel', '.zoom-container', zoom.userEvent); 

这样您就不会在每次出现新元素时都附加一个新的事件监听器。

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 2015-12-14
    • 2022-10-20
    • 2020-01-07
    • 2010-10-17
    • 2010-12-29
    • 2011-08-02
    • 2018-09-30
    相关资源
    最近更新 更多