Ajax只被调用一次

ray*_*ygo 0 html javascript ajax jquery

我有一个关注和取消关注按钮.当然,当您单击"关注"按钮时,应显示取消关注按钮.单击"关注"按钮时,应显示"取消关注"按钮.

截至目前,当您点击"关注"时,数据库会更新,"关注"按钮消失,并显示"取消关注"按钮.问题是,如果我再次点击"取消关注"按钮,则没有任何反应.即使我放了一个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>')
                 );
               }
          });           

    });    

});
Run Code Online (Sandbox Code Playgroud)

HTML:

关注按钮:

<div id="followButton">                 
  <a href="#" class="button follow" id="0-p-0">+ follow</a>
</div>
Run Code Online (Sandbox Code Playgroud)

取消关注按钮:

<div id="followButton">
        <a href="#" class="button unfollow" id="unfollow_0">- unfollow</a></div>
Run Code Online (Sandbox Code Playgroud)

Fel*_*lix 5

由于您的按钮已通过AJAX调用动态添加到DOM.您需要使用事件委派来在这些元素上附加click事件:

事件委托允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有子项触发,无论这些子项现在是存在还是将来添加.

$(document).on('click','.unfollow', function(){
    // Your code here
});
Run Code Online (Sandbox Code Playgroud)