Javascript,Socket.io - 警报显示不止一次

时间:2016-02-14 11:25:10

标签: javascript jquery node.js sockets socket.io

当我单击跟随按钮时,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;
  }
你可以帮我解决这个问题吗?谢谢!

2 个答案:

答案 0 :(得分:0)

我对于想要实现的目标略显不清楚,但我发现你的代码中存在错误。

此代码应位于$('.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!');
      }
  });

答案 1 :(得分:0)

尝试将#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> struct stat buffer; int status; status = stat("path to file", &buffer); if(status == 0) { // size of file is in member buffer.st_size; } 放在点击回调函数之外,如果仍然无法正常工作,我需要观察服务器代码。