P粉4634184832023-08-22 12:35:21
You can use inline events like this onsubmit
<form onsubmit="alert('停止提交'); return false;">
or
<script> function toSubmit(){ alert('我不会提交'); return false; } </script> <form onsubmit="return toSubmit();">
Now, when developing large projects, this is probably not a good idea. You may need to use event listeners.
Please read more about inline events vs event listeners (addEventListener and IE's attachEvent) here . Because I can't explain it better than Chris Baker.
P粉3995850242023-08-22 11:25:35
Unlike other answers, returning false
is only the part of the answer. Consider the case where a JS error occurs before the return statement...
html
<form onsubmit="return mySubmitFunction(event)"> ... </form>
script
function mySubmitFunction() { someBug() return false; }
Returning false here
will not be executed and the form will be submitted in any way. You should also call preventDefault
to prevent the default action of Ajax form submission.
function mySubmitFunction(e) { e.preventDefault(); someBug(); return false; }
In this case, even if there is an error, the form will not be submitted!
Alternatively, you can use the try...catch
block.
function mySubmit(e) { e.preventDefault(); try { someBug(); } catch (e) { throw new Error(e.message); } return false; }