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

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

问题描述

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



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

解决方案

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

例如:

 < script> 
函数doSomething(){
alert('Form submitted!');
返回false;
}
< / script>

< form onsubmit =return doSomething();类=我的形式>
< input type =submitvalue =提交>
< / form>

这可以起作用,但最好不要用JavaScript来抛弃HTML,就像你不应该写大量的嵌入式CSS规则。许多Javascript框架促进了这种关注的分离。在jQuery中,您使用JavaScript代码绑定事件,如下所示:

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

< form class =my-form>
< input type =submitvalue =提交>
< / form>


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.

解决方案

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.

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:

<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天全站免登陆