jQuery的replaceWith()是否也删除了事件处理程序?

时间:2011-10-19 15:38:18

标签: jquery

我已经通过jQuery文档查看了这个简单问题的答案:

  

replaceWith()是否会呼叫remove()detach()

我对官方文件没有好运;它被明确地定义为删除节点。但测试显示内存泄漏。

3 个答案:

答案 0 :(得分:16)

查看jQuery(2.1.1)的源代码,你会问两个不同的问题。

  1. jQuery的replaceWith()会删除事件处理程序吗?

    是。 jQuery calls cleanData(),这是一个删除元素上所有数据的内部方法。由于jQuery事件处理程序存储在元素数据中,因此它们也将被清理。

    cleanData() 通过调用jQuery.removeEvent()(另一个内部方法)删除附加到元素的事件处理程序,该事件处理程序触发存储在元素数据中的所有事件处理程序的执行

  2. replaceWith()是否会呼叫remove()detach()

    如果没有向remove()提供任何参数,则仅调用时间<{1}}; jQuery将其视为您正在调用replaceWith()而不是remove();


  3. TL; DR :jQuery将为您清理所有内容,因此不存在内存泄漏的风险。

答案 1 :(得分:4)

如果你不想要这个行为看看这个讨论得很差的jQuery门票的话题 http://bugs.jquery.com/ticket/13400

对于那些不准备期待代码的人,这里是使用replaceWith代替detach的{​​{1}}的实现

with remove()

remove

with detach()

old.replaceWith( new );

答案 2 :(得分:0)

1) A.ReplaceWith(B); ,它将删除A元素和所有附加事件。 B的所有事件都必须声明

2) A.before(B).detach(); ;它将删除A元素,但 keep事件供以后使用(并且仅适用于A)。 B的所有事件都必须声明

可以通过使用下面的代码中的事件传播或事件冒泡来解决此问题

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ 
  $(".rp").click(function(){
    let variable1 = parseInt($(this).text(), 10) + 6;
    $(this).replaceWith("<button class='rp'>"+ variable1 + "</button>");

   });

   $(".detach").click(function(){
    let variable1 = parseInt($(this).text(), 10) + 6;
    $(this).replaceWith("<button class='detach'>"+ variable1 + "</button>");

   });

   $("body").on("click", ".detach2",function(){
    let variable1 = parseInt($(this).text(), 10) + 6;
    $(this).replaceWith("<button class='detach2'>"+ variable1 + "</button>");
   });

   $("body").on("click", ".detach3",function(){
    let variable1 = parseInt($(this).text(), 10) + 6;
    $(this).before("<button class='detach3'>"+ variable1 + "</button>"). detach();
   });

});
</script>
</head>
<body>

<h1>This is a heading</h1>

<p>with ReplaceWith <button class="rp">1</button></p>
<p>with before / detach <button class="detach">2</button> </p>
<p>with ReplaceWith correct event bubbling <button class="detach2">3</button> </p>
<p>with before / detach and correct event bubbling <button class="detach3">4</button> </p>

</body>
</html>

希望对某人有帮助...