English 中文(简体)
替换后事件无法注册
原标题:
  • 时间:2009-04-20 22:07:12
  •  标签:

当我使用replaceWith将一个元素从DOM中移出,然后再将其replaceWith回去时,绑定在它上面的事件不会触发。 我需要事件保持完整。

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

现场演示

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)后,您需要重新附加click事件处理程序到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);
});
问题回答

更新:`live()`和`bind()`已经弃用,改用`on()`。

You can use live() and bind() events, this is your new code:

$(function() {
$( .x ).live( click , function() {
    var replacement = $(document.createElement( span ));
    var original = $(this).replaceWith(replacement);

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

-Live event works with jQuery 1.3 and upper.

-if you want to stop the live propagation use die() function.

live events are what you are looking for





相关问题
热门标签