在您的blur 处理程序中,您必须对浏览器进行“让步”(setTimeout、异步 ajax 调用等),否则浏览器将不会中断您的 JavaScript 代码提交表格。请参阅下面的示例来证明这一点。
如果您正在在 blur 处理程序中执行让浏览器产生的操作,则必须使用 submit 处理程序阻止表单提交,然后在何时提交一切(包括blur 处理程序中的各种操作)都准备好了。这可能有点复杂。
最好的答案是删除 blur 处理程序中让浏览器处理的所有内容。如果您不能这样做,您可能正在查看表单上的锁定计数器并让提交处理程序检查该锁定计数器:
// Somewhere, ensure the form has a lock count of zero
$('#theForm').data('submitlock', 0);
// Your blur handler increments the lock
// In the blur handler:
$('#theForm').data('submitlock', $('#theForm').data('submitlock') + 1);
// ...and when done
$('#theForm').data('submitlock', $('#theForm').data('submitlock') - 1);
// The submit handler might look something like this:
$('#theForm').submit(function() {
// Get a jQuery wrapper for the form
var $this = $(this);
// Locked?
if ($this.data('submitlock') > 0) {
// Yes, set up the recheck and prevent form submission
setTimeout(recheck, 10);
return false;
}
// Function to periodically retry submission
function recheck() {
// Still locked?
if ($this.data('submitlock') > 0) {
// Keep waiting
setTimeout(recheck, 10);
}
else {
// Nope, submit the form using the underlying DOM object's submit function
$this[0].submit();
}
}
});
Live example(下面我们阻止示例的一个版本,但已更新为让给浏览器)
请注意,如果您的表单被提交到新窗口,您可能会遇到弹出窗口阻止程序(因为新窗口不会直接响应用户点击)。但是,如果您不做类似的事情,那么您在上述情况下处于良好状态。
下面是 blur 处理程序的示例,该处理程序在提交表单 (live copy) 之前导致大量延迟(四秒):
HTML:
<form action='http://www.google.com/search' target='_new'>
<label>Search for:
<input type='text' name='q' value='foo'></label>
<br><input type='submit' value='Search'>
</form>
JavaScript:
$('input[name=q]').blur(function() {
var end, counter;
display("Start blurring");
counter = 0;
end = new Date().getTime() + 4000;
while (new Date().getTime() < end) {
++counter;
if (counter % 100000 == 0) {
display("Still blurring");
}
}
display("Done blurring");
});
将光标放在文本框中,然后单击“搜索”。您会看到 4 秒的延迟,然后搜索将在新窗口中打开。我已经在 Chrome、Firefox 和 Opera(Linux 上)、Windows 2000 上的 IE6 和 Windows XP 上的 IE7 上测试过这个。所有人的行为方式都一样。