【问题标题】:JavaScript disconnect after jQuery replaceWith()jQuery replaceWith() 后 JavaScript 断开连接
【发布时间】:2012-07-27 19:53:26
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: javascript jquery asp.net-mvc twitter-bootstrap


    【解决方案1】:

    事件委托。

    $(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/

    不要将事件绑定到将被移除的按钮(从而丢失事件绑定),而是将其绑定到一个不会被移除但是该按钮的祖先的元素。

    【讨论】:

    • 另外,只是一个小提示,您可以将new Date().getTime()替换为$.now()
    • @KevinB:或者Date.now(),哦等等,更短。 :-P
    【解决方案2】:

    不要在文档上绑定事件处理程序(如 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)
    });
    

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 2013-05-17
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 2012-08-07
      相关资源
      最近更新 更多