javascript 如何在 jQuery submit() 执行之前运行代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8263988/
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
How can I run code right before the jQuery submit() executes?
提问by Leo Jiang
Basically, I have a form and a validation function that executes when a form is submitted. However, I want some other codes to run before the validation runs. I tried this: How to order events bound with jQuery, but it does not work.
基本上,我有一个表单和一个在提交表单时执行的验证函数。但是,我希望在验证运行之前运行一些其他代码。我试过这个:如何订购与 jQuery 绑定的事件,但它不起作用。
Here's what I have:
这是我所拥有的:
$('form').submit(function(){
$('form').trigger('before-submit');
if($(this).find('error').exists(event))
event.preventDefault();
});
$('form').bind('before-submit', function(e) {
if($('#url').val=='http://')
$('#url').val('');
alert('test');
});
回答by Sudhir Bastakoti
You could do:
你可以这样做:
$(function() { $('#formLogin').submit( function() { alert("Something"); //do something else here return true; }); });
回答by Sander
how about this:
这个怎么样:
$('form').submit(function(){
beforeSubmit(function(){
// this function is the 'callback' function
if($(this).find('error').exists(event))
event.preventDefault();
});
});
function beforeSubmit(fn) {
if($('#url').val=='http://'){
$('#url').val('');
alert('test');
}
// call the 'callback' function you gave as argument
fn();
}