表单提交执行 JavaScript 最佳实践?

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

Form Submit Execute JavaScript Best Practice?

javascripthtmlforms

提问by gberg927

I would like to run a JavaScript function when a form is submitted. The issue is that, when the form is submitted, the page is reloaded and the form values are appended to the URL as GET parameters. I would like it to stay on the current page and only run the JavaScript function.

我想在提交表单时运行 JavaScript 函数。问题在于,提交表单时,页面会重新加载,并且表单值会作为 GET 参数附加到 URL。我希望它停留在当前页面上并且只运行 JavaScript 函数。

I was wondering what the best practice (or what you do) to avoid having the page reload and parameters be sent.

我想知道避免重新加载页面和发送参数的最佳实践(或您做什么)。

回答by moteutsch

Use the onsubmitevent to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefaultmethod to disable the form submission.

使用该onsubmit事件在提交表单时执行 JavaScript 代码。然后您可以返回 false 或调用传递的事件的preventDefault方法来禁用表单提交。

For example:

例如:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

这是有效的,但最好不要用 JavaScript 乱扔 HTML,就像您不应该编写大量内联 CSS 规则一样。许多 Javascript 框架促进了这种关注点分离。在 jQuery 中,您可以使用 JavaScript 代码绑定事件,如下所示:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

回答by Martin

I know it's a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.

我知道这有点晚了。但我一直认为创建事件监听器的最佳方式是直接从 JavaScript 中创建。有点像不应用内联 CSS 样式。

function validate(){
    //do stuff
}
function init(){
    document.getElementById('form').onsubmit = validate;
}
window.onload = init;

That way you don't have a bunch of event listeners throughout your HTML.

这样你的 HTML 中就没有一堆事件侦听器。

回答by Quentin

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

将事件处理程序附加到表单的提交事件。确保它取消默认操作。

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUIand jQuery) include event handling features, and there is a large collection of tiny event libraries.

Quirks Mode 有一个关于事件处理程序的指南,但您最好使用库来简化代码并消除浏览器之间的差异。所有主要的(例如YUIjQuery)都包含事件处理功能,并且有大量小型事件库

Here is how you would do it in YUI 3:

以下是您在 YUI 3 中的做法:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slackif the JavaScript fails for any reason.

确保如果 JavaScript 因任何原因失败,服务器将弥补不足