Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - 如何防止表格被提交?(How to prevent form from being submitted?)

I have a form that has a submit button in it somewhere.(我有一个表单,其中某处有一个提交按钮。)

However, I would like to somehow 'catch' the submit event and prevent it from occurring.(但是,我想以某种方式“捕获”提交事件并防止它发生。) Is there some way I can do this?(有什么办法可以做到这一点?) I can't modify the submit button, because it's part of a custom control.(我无法修改“提交”按钮,因为它是自定义控件的一部分。)   ask by Nathan Osman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unlike the other answers, return false is only part of the answer.(与其他答案不同,返回false只是答案的一部分 。)

Consider the scenario in which a JS error occurs prior to the return statement...(考虑在return语句之前发生JS错误的情况...) html(html) <form onsubmit="return mySubmitFunction(event)"> ... </form> script(脚本) function mySubmitFunction() { someBug() return false; } returning false here won't be executed and the form will be submitted either way.(返回false将不会执行,并且将以任何一种方式提交表单。) You should also call preventDefault to prevent the default form action for Ajax form submissions.(您还应该调用preventDefault以阻止Ajax表单提交的默认表单操作。) function mySubmitFunction(e) { e.preventDefault(); someBug(); return false; } In this case, even with the bug the form won't submit!(在这种情况下,即使存在错误,表单也不会提交!) Alternatively, a try...catch block could be used.(或者,可以使用try...catch块。) function mySubmit(e) { e.preventDefault(); try { someBug(); } catch (e) { throw new Error(e.message); } return false; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...