出于某种原因,尽管此代码确实刷新了页面,但没有任何字段被发布...
$('form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
有更好的编码方式吗?
您的代码正在改变表单的提交操作。它会更改按钮属性,而不是执行提交操作。
请尝试以下代码:
$('input[type=submit]').click(function() {
$(this).attr('disabled', 'disabled');
$(this).parents('form').submit();
});
我见过几种方法来实现这个:
但是没有一种方法能够像预期的那样工作,所以我自己想出了一种方法。
在您的表单中添加一个名为submit-once
的类,并使用以下 jQuery 代码:
$('form.submit-once').submit(function(e){
if( $(this).hasClass('form-submitted') ){
e.preventDefault();
return;
}
$(this).addClass('form-submitted');
});
这会向您的表单添加另一个类:form-submitted
。然后,如果您尝试重新提交具有此类的表单,jQuery将阻止表单提交并在 return;
处退出函数,因此不会重新提交。
我选择使用$('form.submit-once')
而不是$('form')
,因为我的一些表单使用Ajax,应该能够提交多次。
您可以在这个 jsFiddle上测试它。我已经向表单中添加了target="_blank"
,以便您可以测试多次提交表单。
附注:您可能希望通过服务器端也防止重复提交来考虑非JS用户。例如,有一个会话变量来存储上次提交的日期/时间,并忽略3秒内的任何进一步提交。
我不知道为什么问题中的代码不能正常工作。这里有一个类似且简单明了的代码片段,我建议你不要过度复杂化。
$("form").submit(function () {
// prevent duplicate form submissions
$(this).find(":submit").attr('disabled', 'disabled');
});
优点:
最终我使用的方法,在Chrome 53上运行良好:
$('input[type=submit]').addClass('submit-once').click(function(e){
if($(this).hasClass('form-submitted') ){
e.preventDefault();
return;
}
$(this).addClass('form-submitted');
});
没有理由你的代码不能正常工作。在提交表单时,提交按钮会被禁用。我检查了演示中传输到JSFiddle的头文件,并确实发送了表单字段(在IE和Chrome中进行了测试):
POST http://fiddle.jshell.net/josh3736/YnnGj/show/ HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://fiddle.jshell.net/josh3736/YnnGj/show/
Accept-Language: en-US,en;q=0.7,es;q=0.3
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: fiddle.jshell.net
Content-Length: 9
Connection: Keep-Alive
Pragma: no-cache
test=It+works
你的代码没问题。我也遇到了同样的问题,但对我来说问题在于php而不是javascript。当你禁用按钮时,它不再随表单一起发送,我的php依赖于提交按钮。
if(isset($_POST['submit'])){
...
}
$('body').bind('pagecreate', function() {
$("#signin-btn").bind('click', function() {
$(this).button('disable');
showProgress(); // The jquery spinny graphic
$('form').submit();
});
});
$(function(){
$(document).on('click', 'input[type=submit], button[type=submit], a.submit, button.submit', function() {
// Preserves element width
var w = $(this).outerWidth();
$(this).css('width', w+'px');
// Replaces "input" text with "Wait..."
if ($(this).is('input'))
$(this).val('Wait...');
// Replaces "button" and "a" html with a
// loading image.
else if ($(this).is('button') || $(this).is('a'))
$(this).html('<img style="width: 16px; height: 16px;" src="path/to/loading/image.gif"></img>');
// Disables the element.
$(this).attr('disabled', 'disabled');
// If the element IS NOT a link, submits the
// enclosing form.
if (!$(this).is('a'))
if ($(this).parents('form').length)
$(this).parents('form')[0].submit();
return true;
})
});
submit
。
name
属性? - emco