jQuery关注/取消关注功能异常:Tweets不自动加载及按钮状态未切换
问题描述
我编写了一段jQuery代码,期望实现以下功能:登录用户点击follow按钮时,被关注用户的Tweets自动显示在dashboard中,同时按钮文本切换为unfollow。但实际运行时,代码虽能完成关注操作并写入数据库,却无法自动切换按钮状态,且Tweets需手动刷新页面才会显示。请帮忙排查需修改的内容,以实现Tweets自动加载及按钮状态自动切换。
当前代码
// Follow or unfollow function document.addEventListener('click', function (event) { if (event.target.classList.contains('follow-btn')) { var userId = event.target.getAttribute('data-userid'); var followBtn = event.target; $.ajax({ type: "POST", url: '/Home/Follow', // URL to send the follow action contentType: "application/json; charset=utf-8", data: JSON.stringify({ UserId: userId }), // UserId property in the FollowUnfollowViewModel model success: function (response) { if (response.success) { // Append the received tweets to the screen response.tweets.forEach(function (tweet) { $('#tweets-container').append( `<div class="tweet" id="tweet-${tweet.Id}"> <time>${new Date(tweet.CreatedAt).toLocaleString()}</time> <p> <strong>${tweet.TwitterUser.FirstName} ${tweet.TwitterUser.LastName}</strong> <span class="text-muted">${tweet.TwitterUser.UserName}</span> </p> <p>${tweet.Content}</p> <div class="tweet-actions"> <i class="fas fa-comment"></i> <i class="fas fa-retweet"></i> <i class="fas fa-heart"></i> </div> </div>` ); }); // Change the follow button to unfollow button followBtn.classList.remove('follow-btn'); followBtn.classList.add('unfollow-btn'); followBtn.textContent = 'Unfollow'; } }, error: function () { } }); } if (event.target.classList.contains('unfollow-btn')) { var userId = event.target.getAttribute('data-userid'); var unfollowBtn = event.target; $.ajax({ type: "POST", url: '/Home/Unfollow', // URL to send the unfollow action contentType: "application/json; charset=utf-8", data: JSON.stringify({ UserId: userId }), // UserId property in the FollowUnfollowViewModel model success: function (response) { if (response.success) { // Remove the tweets of the unfollowed user from the screen response.tweets.forEach(function (tweet) { document.getElementById(`tweet-${tweet.Id}`).remove(); }); // Change the unfollow button to follow button unfollowBtn.classList.remove('unfollow-btn'); unfollowBtn.classList.add('follow-btn'); unfollowBtn.textContent = 'Follow'; } }, error: function () { } }); } });
排查与修改方案
修正事件目标匹配逻辑:如果按钮内部包含子元素(如图标),
event.target会指向子元素而非按钮本身,导致逻辑不触发。改用closest()方法向上查找按钮元素:// 替换follow-btn判断逻辑 var followBtn = event.target.closest('.follow-btn'); if (followBtn) { var userId = followBtn.getAttribute('data-userid'); // 后续AJAX逻辑不变 } // 替换unfollow-btn判断逻辑 var unfollowBtn = event.target.closest('.unfollow-btn'); if (unfollowBtn) { var userId = unfollowBtn.getAttribute('data-userid'); // 后续AJAX逻辑不变 }验证后端返回数据有效性:在AJAX的success回调中添加日志,确认
response.success是否为true,以及response.tweets是否包含有效数据:success: function (response) { console.log(response); // 查看返回数据结构 if (response.success) { // 原有逻辑 } }若后端未正确返回
tweets数组或success为false,需先修复后端接口。优化按钮状态切换操作:可改用jQuery方法简化DOM操作,避免原生方法的兼容性问题:
// 替换follow按钮状态切换代码 $(followBtn).removeClass('follow-btn').addClass('unfollow-btn').text('Unfollow'); // 替换unfollow按钮状态切换代码 $(unfollowBtn).removeClass('unfollow-btn').addClass('follow-btn').text('Follow');调整推文追加顺序(可选):若希望新推文按时间倒序显示,将
append改为prepend,把新推文放在容器最顶部:$('#tweets-container').prepend(/* 推文HTML代码 */);添加错误回调日志:在AJAX的error回调中添加错误信息输出,方便排查请求失败问题:
error: function (xhr, status, error) { console.error('请求失败:', error); }
内容的提问来源于stack exchange,提问作者Corewien
相关产品推荐
相关产品推荐

