javascript - Ajax 只被调用一次

标签 javascript jquery html ajax

我有一个关注和取消关注按钮。当然,当您单击关注按钮时,应该会出现取消关注按钮。当您单击关注按钮时,应该会出现取消关注按钮。

截至目前,当您单击“关注”时,数据库会更新,“关注”按钮消失,“取消关注”按钮出现。问题是,如果我再次单击“取消关注”按钮,什么也不会发生。即使我放了一个 console.log('test');在脚本之上,没有任何效果。这是我的代码:

Javascript:

$(document).ready(function(){
    console.log('test');

    $('.follow').click(function(){
        console.log('yes');
            var userid = $(this).attr("id");
            var dataString = 'id='+ userid ;
            var self = this;                
              $.ajax({
                    type: "POST",
                    url: "/ajax/follow",
                    data: dataString,
                    success: function(result) {
                        var json = $.parseJSON(result);
                            $(self).remove();
                        $('#followButton').append(                                     
                     $('<a href="#" class="button unfollow" id="unfollow_'+ json +'">- unfollow</a>')
                );
                }
              });
    });
    $('.unfollow').click(function(){
        console.log('no');
        var id = $(this).attr("id");
        var dataString = 'id='+ id ;
        var self = this;            
        $.ajax({
                type: "POST",
                url: "/ajax/unfollow",
                data: dataString,
                success: function(result) {    
                    $(self).remove();                       
                    $('#followButton').append(                                     
                $('<a href="#" class="button follow" id="'+ result +'">+ follow</a>')
                 );
               }
          });           

    });    

});

HTML:

关注按钮:

<div id="followButton">                 
  <a href="#" class="button follow" id="0-p-0">+ follow</a>
</div>

取消关注按钮:

<div id="followButton">
        <a href="#" class="button unfollow" id="unfollow_0">- unfollow</a></div>

最佳答案

因为您的按钮已通过 AJAX 调用动态添加到 DOM。您需要使用event delegation 在这些元素上附加点击事件:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.

$(document).on('click','.unfollow', function(){
    // Your code here
});

关于javascript - Ajax 只被调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23157897/

相关文章:

javascript - 函数与对象构造函数

javascript - 用JS创建带有onMouseOver效果的DIV

javascript - 将 View 连接到 Backbone 中的集合

javascript - CRC32 每次都返回新整数

javascript - HTML 会影响 ajax 调用吗

javascript - CK Editor 的 Edit Content 对特定单词更改为 readonly

jQuery post on window.unload(窗口或浏览器关闭)

javascript - 为什么 margin 仅在 .info 处于事件状态时适用

javascript - 如何使用 AngularJs 通过 id 删除数据?

html - 隐藏菜单中的谷歌地图