replaceWith 后事件未注册 [英] Events not registering after replaceWith

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

问题描述

当我 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).

推荐答案

因为当您替换原始元素时,绑定到它的事件将被删除.在调用 replacement.replaceWith(original) 后,您需要在 original 上重新附加 click 事件处理程序:

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);
});

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

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