我怎样才能在javascript中听表单提交事件? [英] How can I listen to the form submit event in javascript?

查看:115
本文介绍了我怎样才能在javascript中听表单提交事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写我自己的表单验证JavaScript库,我一直在寻找谷歌如何检测是否点击提交按钮,但我发现的是代码,你必须使用点击 onSubmit = function() in html。



我想制作这个javascript,以便我不必触摸任何html代码添加onSubmit或onClick javascript。

解决方案

在香草javascript中编写事件处理程序可能会让浏览器工作变得烦人,建议使用像 jquery 这样的库,以使其健壮(也更容易编写)。



在jquery中,如果你有这样的表单:

 < form id =hello-世界action =sayhello> 
< input type =submitvalue =Hello!>
< / form>

您可以添加如下的事件处理程序:

  $('#hello-world')。submit(function(ev){
ev.preventDefault(); //停止表单提交
/ *验证到这里* /
this.submit(); //如果所有验证成功
});


I wanna write my own form validation javascript library and I've been looking on google how to detect if a submit button is clicked but all I found is code where you have to use onClick on onSubmit="function()" in html.

I would like to make this javascript so that I don't have to touch any html code like adding onSubmit or onClick javascript.

解决方案

Writing event handlers in vanilla javascript can be annoying to make work across browsers, so I'd recommend using a library like jquery to make it robust (and also easier to write).

In jquery, if you have a form like this:

<form id="hello-world" action="sayhello">
    <input type="submit" value="Hello!">
</form>

You can attach an event handler like this:

$('#hello-world').submit(function(ev) {
    ev.preventDefault(); // to stop the form from submitting
    /* Validations go here */
    this.submit(); // If all the validations succeeded
});

这篇关于我怎样才能在javascript中听表单提交事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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