jQuery 防止通过 event.preventDefault() 提交表单;不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15051128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent form from submitting via event.preventDefault(); not working
提问by BrownChiLD
I'm using jQuery to submit my form variables, and im trying to prevent the form from submitting via the usual ways (click submit button or press enter on one of the fields)
我正在使用 jQuery 提交我的表单变量,并且我试图阻止表单通过通常的方式提交(单击提交按钮或在其中一个字段上按 Enter)
i have this:
我有这个:
$('#form').submit(function(){
event.preventDefault();
});
but it doesn't seem to work my form is still submitting, going to the process.php page..
但它似乎不起作用我的表单仍在提交,转到 process.php 页面..
回答by steveukx
If the only thing you need to do is to prevent the default action, you can supply false
instead of a function:
如果您唯一需要做的就是阻止默认操作,您可以提供false
而不是函数:
$('#form').submit(false);
回答by Rob
try return false
instead of event.preventDefault()
or accept event
as a parameter of your function.
尝试return false
代替event.preventDefault()
或接受event
作为函数的参数。
$('#form').submit(function(event){
event.preventDefault();
});
Not sure why some people think this no longer works but here is an example showing it does still work.
不知道为什么有些人认为这不再有效,但这里有一个例子表明它仍然有效。
https://jsfiddle.net/138z5atq/
https://jsfiddle.net/138z5atq/
Comment out the event handler and it will alert.
注释掉事件处理程序,它会发出警报。
Regarding stopPropagation()
and stopImmediatePropagation()
they don't prevent the form from submitting at all. They just prevent the event from bubbling up the dom.
关于stopPropagation()
并且stopImmediatePropagation()
他们根本不阻止表单提交。他们只是防止事件冒泡 dom。
回答by dr.dimitru
Other way is:
另一种方式是:
$('#form').submit(function(){
//some code here
return false;
});
回答by JavaJudt
I wasn't able to get the posted answers to work, and only supplying false was not an option for me. I found this to work:
我无法获得已发布的答案,并且仅提供 false 对我来说不是一个选择。我发现这有效:
$(document).on('submit', '#form', function(event){
event.preventDefault();
});