Javascript 在提交之前如何做一些事情?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8053394/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:31:49  来源:igfitidea点击:

How to do something before on submit?

javascriptjqueryhtml

提问by Jimmy

i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClickon that button but it happens after the submit.

我有一个表单,它有一个提交表单的按钮。我需要在提交之前做一些事情。我试着在那个按钮上做onClick但它发生在提交之后。

I can't share the code but, generally, what should I do in jQuery or JS to handle this?

我不能分享代码,但一般来说,我应该在 jQuery 或 JS 中做什么来处理这个问题?

回答by Dan Breen

If you have a form as such:

如果您有这样的表格:

<form id="myform">
...
</form>

You can use the following jQuery code to do something before the form is submitted:

您可以使用以下 jQuery 代码在提交表单之前执行某些操作:

$('#myform').submit(function() {
    // DO STUFF...
    return true; // return false to cancel form action
});

回答by acme

Assuming you have a form like this:

假设你有一个这样的表格:

<form id="myForm" action="foo.php" method="post">
   <input type="text" value="" />
   <input type="submit" value="submit form" />

</form>

You can attach a onsubmit-event with jQuery like this:

您可以onsubmit像这样使用 jQuery附加一个-event:

$('#myForm').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

If you return falsethe form won't be submitted after the function, if you return true or nothing it will submit as usual.

如果您return false在函数之后不会提交表单,如果您返回 true 或什么都不提交,它将照常提交。

See the jQuery documentationfor more info.

有关更多信息,请参阅jQuery 文档

回答by James Johnson

You can use onclickto run some JavaScript or jQuery code before submitting the form like this:

您可以使用onclick在提交表单之前运行一些 JavaScript 或 jQuery 代码,如下所示:

<script type="text/javascript">
    beforeSubmit = function(){
        if (1 == 1){
            //your before submit logic
        }        
        $("#formid").submit();            
    }
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />

回答by rogerlsmith

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

确保提交按钮不是“提交”类型,使其成为按钮。然后使用 onclick 事件触发一些 javascript。在实际发布数据之前,您可以在那里做任何想做的事情。