在页面提交前直接执行 javascript 代码

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

Execute javascript code straight before page submit

javascript

提问by ale

There are a few similar questions to this but none quite the same.

有一些与此类似的问题,但没有一个完全相同。

I want to know if there is an event that can be used to execute some JS before a page is submitting (i.e. POSTed).

我想知道是否有一个事件可以用于在页面提交(即发布)之前执行一些 JS。

采纳答案by Laurynas

If you are working with the form, you can use onsubmitevent.

如果您正在使用表单,则可以使用onsubmit事件。

Using jQuery you can do that with

使用 jQuery 你可以做到这一点

$('#myform').submit(function() {
  // your code here
});

回答by Moe Sweet

Something like this?

像这样的东西?

<form onsubmit="do_something()">

function do_something(){
   // Do your stuff here
}

If you put returnlike the code below, you can prevent the form submission by returning false from the do_something()function.

如果您return像下面这样放置代码,则可以通过从do_something()函数返回 false 来阻止表单提交。

<form onsubmit="return do_something()">

function do_something(){
   // Do your stuff here
   return true; // submit the form

   return false; // don't submit the form
}

回答by James Allardice

You can bind an event handler to the submitevent (following code assumes you have an idon your form):

您可以将事件处理程序绑定到submit事件(以下代码假定您的id上有form):

document.getElementById("someForm").onsubmit = function() {
    //Do stuff
};

回答by Julien Bourdon

Yes, you can use on the onsubmitevent on your form.

是的,您可以onsubmit在表单上的事件上使用。

In pure HTML (without jQuery), you can use:

在纯 HTML(没有 jQuery)中,您可以使用:

<form onSubmit="mySubmitFunction()">
   ...
</form>

More details here: https://www.w3schools.com/jsref/event_onsubmit.asp

更多细节在这里:https: //www.w3schools.com/jsref/event_onsubmit.asp

回答by Vince Pike

The following code will abort the submission from the window level, which will not submit the form.

以下代码将从窗口级别中止提交,不会提交表单。

window.onsubmit = function() { alert('aborting submit'); return false; };

Tested with IE11, so it should work for some legacy applications without jQuery.

用 IE11 测试,所以它应该适用于一些没有 jQuery 的遗留应用程序。