我正在尝试制作一个关注/取消关注按钮。关注按钮效果很好。单击时,我将按钮 id 更改为“unfollow”,但是当我再次单击该按钮时(当它的 id 为“unffollow”时),它的行为就好像它仍然具有“follow”的 id,这意味着它仍在使用第一个 ajax 方法如下:
$("#fbtn").on('click',function(){
var fbtn = $('#fbtn');
var followee_name = $('#author').text();
$.ajax({
url: '/follow',
method: 'POST',
//dataType: 'application/json',
data:{followee_name:followee_name},
success: function(response){
console.log("Followed")
fbtn.text('Unfollow');
fbtn.attr('id','unfollow');
}
});
});
然后:
$("#unfollow").on('click',function(){
var unfollowbtn = $('#unfollow');
$.ajax({
url: '/unfollow',
method: 'DELETE',
//dataType: 'application/json',
success: function(response,err){
if(err){
console.log(err);
}
console.log("Unfollowd")
unfollowbtn.text('Follow');
unfollowbtn.attr('id','fbtn');
}
});
});
HTML:
<a id="author" href="#"><%= showPost.username %></a> //this displays a username
<button style="width:100px;" type="button" id="fbtn">Follow</button>
我不知道我错在哪里,理论上这对我来说看起来不错,但我对 jquery 和 ajax 很陌生,我一定错过了一些东西。
最佳答案
您不必更改 ID 并为此编写 JS,而只需更改类并在代码中使用该类:
$("#fbtn").on('click', function() {
var fbtn = $(this);
if (fbtn.hasClass('follow')) {
fbtn.removeClass('follow').addClass('unfollow');
fbtn.text('Unfollow');
} else {
fbtn.removeClass('unfollow').addClass('follow');
fbtn.text('Follow');
}
console.log('New Class: ' + fbtn.attr('class'));
/*$.ajax({
url: '/follow-unfollow',
method: 'DELETE',
success: function(response, err) {
if (err) {
console.log(err);
}
console.log("Unfollowd")
}
});
*/
});
.follow {
background: red;
}
.unfollow {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button style="width:100px;" class='follow' type="button" id="fbtn">Follow</button>
关于jquery - 使用ajax和jquery更改id后按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48558851/