我有一个关注和取消关注按钮。当然,当您单击关注按钮时,应该会出现取消关注按钮。当您单击关注按钮时,应该会出现取消关注按钮。
截至目前,当您单击“关注”时,数据库会更新,“关注”按钮消失,“取消关注”按钮出现。问题是,如果我再次单击“取消关注”按钮,什么也不会发生。即使我放了一个 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/