Javascript,Socket.io - 警报出现不止一次

Javascript, Socket.io - alert shows up more than one time

本文关键字:不止一次 Socket io Javascript      更新时间:2023-09-26

当我点击关注按钮时,socket.io 向服务器发送一些数据,然后服务器发回一个响应号。根据数字是多少,js 会发出警报。但是如果我第二次单击该按钮,js 将两次提醒相同的消息,如果我再次单击它,则三次,依此类推。如果我刷新页面,它会重新开始(单击一次,警报显示一次,单击两次,警报显示两次......

代码如下:

$('.followUser').click(function(e){
  e.stopImmediatePropagation();
  e.preventDefault();
  var user= $(this).parent().parent().parent().parent().next().children().children('.userName').children().first().children().attr('id');
  var thisUserId = $.cookie('thisUserID');
  if(user != thisUserId){ //if he tries to follow himself
    var object = {
      user: user,
      userId: thisUserId
    }
    socket.emit('followUser', object); //server just adds that user to the following list of the first user
    socket.on('followUserResults', function(data){
      if(data == 1){
        alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
      } else if(data == 0){
        alert('User was added to your following list!');
      } else if(data == 2){
        alert('This user is already on your following list!');
      }
    });
  } else {
    return false;
  }

你能帮我吗?谢谢!

我有点不清楚要实现什么,但我立即注意到您的代码中存在错误。

此代码应位于$('.followuser').click函数之外:

socket.on('followUserResults', function(data){
      if(data == 1){
        alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
      } else if(data == 0){
        alert('User was added to your following list!');
      } else if(data == 2){
        alert('This user is already on your following list!');
      }
    });

所以你的代码应该读成这样:

$('.followUser').click(function(e){
    e.stopImmediatePropagation();
    e.preventDefault();
    var user= $(this).parent().parent().parent().parent().next().children().children('.userName').children().first().children().attr('id');
    var thisUserId = $.cookie('thisUserID');
    if(user != thisUserId){ //if he tries to follow himself
        var object = {
            user: user,
            userId: thisUserId
        }
        socket.emit('followUser', object); //server just adds that user to the following list of the first user
    } else {
        return false;
}
socket.on('followUserResults', function(data){
      if(data == 1){
          alert('Something went wrong! Please refresh this page and try again'); // if they changed the id on html
      } else if(data == 0){
          alert('User was added to your following list!');
      } else if(data == 2){
          alert('This user is already on your following list!');
      }
  });

尝试将socket.on(...)放在单击回调函数之外,如果仍然无法正常工作,我需要观看服务器代码。