活动没有注册后替换 [英] Events not registering after replaceWith

查看:117
本文介绍了活动没有注册后替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我 replaceWith 将元素从DOM中移出时,则 replaceWith 不要开火了我需要事件保持不变。

When I replaceWith an element to bring one out of the DOM, then replaceWith it back in, events registered to it do not fire. I need to events to remain intact.

这是我的Javascript:

Here's my Javascript:

var replacement = $(document.createElement('span'));
var original = $(this).replaceWith(replacement);

replacement
    .css('background-color', 'green')
    .text('replacement for ' + $(this).text())
    .click(function() {
        replacement.replaceWith(original);
    });

现场演示

在演示中,单击元素时,将被替换另一个元素使用 replaceWith 。当您单击新元素时,将使用 replaceWith 替换原始元素。但是,点击处理程序不再工作(我认为应该是)。

In the demo, when you click an element, it is replaced with another element using replaceWith. When you click the new element, that is replaced with the original element using replaceWith. However, the click handler does not work any more (where I would think it should).

推荐答案

因为更换原始元素,绑定到它的事件被删除。调用后,您需要重新附加点击事件处理程序原始 replace.replaceWith(原始)

Because when you replace the original element, events bound to it are removed. You'll need to re-attach the click event handler on original after the call to replacement.replaceWith(original):

$(function() 
{   
   function replace() 
   {
      var replacement = $(document.createElement('span'));
      var original = $(this).replaceWith(replacement);

      replacement
         .css('background-color', 'green')
         .text('replacement for ' + $(this).text())
         .click(function() 
         {
            replacement.replaceWith(original);
            original.click(replace);
         });
   }

   $('.x').click(replace);
});

这篇关于活动没有注册后替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆