Javascript,Socket.io - 警报出现不止一次
Javascript, Socket.io - alert shows up more than one time
当我点击关注按钮时,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(...)
放在单击回调函数之外,如果仍然无法正常工作,我需要观看服务器代码。
相关文章:
- KnockoutJS绑定每个文档不止一次
- 控制不止一次跳水的风格's风格使用java脚本动态,使用类
- 随机图像显示不止一次
- XMLhttpRequest Ajax PHP 运行不止一次
- 看起来我的每个循环都循环不止一次
- 骨干 js 模型 保存不止一次
- Javascript,Socket.io - 警报出现不止一次
- 阿贾克斯不止一次打电话
- 我怎样才能防止这种“点击”发生不止一次
- chrome扩展///我的代码运行了不止一次
- 角度控制器触发不止一次.只有某些
- 如何将一个字符算作一个字符,即使它出现不止一次
- 为什么"结束”;音频html5的事件触发不止一次
- 不要做不止一次,要做一段时间,但不要做
- noitification创建的chrome扩展api没有;不要出现不止一次
- 如何使用Jquery/JavaScript使此图像滑块在单击时滑动不止一次
- 为什么可以't我使用HTML5音频标签播放声音不止一次
- 我如何调用setInterval不止一次
- 在ASP中AJAX加载了PartialView.. NET MVC -脚本运行不止一次
- 音频重复不止一次