表单提交执行 JavaScript 最佳实践? [英] Form Submit Execute JavaScript Best Practice?

查看:37
本文介绍了表单提交执行 JavaScript 最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我想知道避免重新加载页面和发送参数的最佳做法(或您所做的)是什么.

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

推荐答案

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

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

例如:

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

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

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

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:

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

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

这篇关于表单提交执行 JavaScript 最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆