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

ale*_*ale 29 javascript

有一些类似的问题,但没有完全相同.

我想知道在页面提交(即POST)之前是否有可用于执行某些JS的事件.

Moe*_*eet 44

像这样的东西?

<form onsubmit="do_something()">

function do_something(){
   // Do your stuff here
}
Run Code Online (Sandbox Code Playgroud)

如果你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
}
Run Code Online (Sandbox Code Playgroud)


Lau*_*nas 25

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

使用jQuery你可以做到这一点

$('#myform').submit(function() {
  // your code here
});
Run Code Online (Sandbox Code Playgroud)

  • 这种方法对我不起作用.表格像往常一样提交. (8认同)
  • @americanknight你需要使用preventDefault方法来停止按钮动作.$('#myform').submit(function(e){e.preventDefault();}); (2认同)

Jam*_*ice 6

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

document.getElementById("someForm").onsubmit = function() {
    //Do stuff
};
Run Code Online (Sandbox Code Playgroud)