每次我单击提交时,jQuery都会不断发布一条额外的消息 [英] jQuery keeps posting an extra message each time I click submit
问题描述
我的jQuery代码表现得很奇怪.每当我单击提交"时,它都会不断发布同一封邮件的额外副本.例如:
My jQuery code is acting really weird. It keeps posting an extra copy of the same message each time I click on submit. For example:
Hello 3
Hello 3
Hello 3
Hello 2
Hello 2
Hello
任何人都知道为什么会这样吗?到目前为止,这是我的代码:
Anyone have an idea why this is happening? Here is my code so far:
jQuery(function ($) {
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message', '<b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val());
$messageTitle.val('');
$messageBox.val('');
}
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
});
推荐答案
此函数在每次调用时都会注册一个事件处理程序.因为您是在click事件中调用它的,所以每次单击时都需要注册一个新的事件处理程序.这些都是在队列中管理的,因此,每次单击按钮时,它将在事件处理程序中运行额外的时间.
This function here registers an event handler every time it's called. Because you're calling it in the click event, every time you click, you register a new event handler. These are managed in a queue, and thus, it will run through the event handler an extra time with each button click.
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
解决方案是将其移到click事件之外.
The solution is to move it outside of the click event.
jQuery(function ($) {
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message', '<b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val());
$messageTitle.val('');
$messageBox.val('');
}
});
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
这篇关于每次我单击提交时,jQuery都会不断发布一条额外的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!