jQuery replaceWith()后JavaScript断开连接

JavaScript disconnect after jQuery replaceWith()

本文关键字:JavaScript 断开 连接 replaceWith jQuery      更新时间:2024-03-18

在我当前创建的应用程序中,我对服务器进行了几次AJAX调用,并用部分视图替换了页面的一部分。除了使用jQuery replaceWith()函数"替换"的按钮外,一切似乎都正常。

在我的实际代码中,我将替换整个<div>,而不仅仅是一个按钮,这里的代码将有助于说明我的问题。

当点击按钮时,JavaScript会被调用,因此,该按钮会被更新。但是,再次尝试单击该按钮,将不会调用或执行相同的JavaScript。这里有一些脱节,我错过了。(在我看来,每次点击类为"updateButton"的按钮时,都应该执行javascript。)请帮帮我。

感谢

事件委派。

$(document).on('click','.updateButton',function (e) {
            e.preventDefault();
    var now = new Date().getTime();
   var newButton = "<span class='btn btn-info updateButton'>Update Button " + now + "</span>"
    $(this).replaceWith(newButton);
});

演示:http://jsfiddle.net/D2RLR/896/

与其将事件绑定到将被删除的按钮(从而丢失事件绑定),不如将其绑定到未被删除但却是该按钮祖先的元素。

不要将事件处理程序绑定到文档上(如Kevin B的回答中所示),只需将其重新绑定到您创建的新按钮即可替换旧按钮。这是一种更有效的事件处理方法,因为在事件触发之前,事件不需要从DOM树一直冒泡到文档。

http://jsfiddle.net/D2RLR/900/

var replaceBtn = function(domBtn,e) {
   e.preventDefault();
   var now = new Date().getTime();
   var newButton = $("<span class='btn btn-info updateButton'>Update Button " + now + "</span>");
    newButton.on('click',function(event) {
        replaceBtn(this,event);
    });
    $(domBtn).replaceWith(newButton);
}
$('.updateButton').click(function(event) {
     replaceBtn(this,event)
});