关于form表单内部回车触发submit的研究
本文由 小茗同学 发表于 2020-02-13 浏览(3023)
最后修改 2020-11-11 标签:form submit

先看示例:

<html>
<body>
	<p>form内任意一个输入框回车都会触发表单提交:</p>
<form onsubmit="handleSubmit(event)">
	<p>姓名: <input type="text" name="name" /></p>
	<p>性别: <input type="text" name="sex" /></p>
	<input id="btn" type="submit" value="提交" onclick="handleClick(event)"/>
</form>
<script>
	// 这里只会触发click事件
	function handleClick(e) {
		e.preventDefault();
		console.log('click', e);
		alert('触发submit按钮的onclick事件');
	}
	function handleSubmit(e) {
		e.preventDefault(); 
		console.log('submit', e);
		alert('触发onSubmit');
	}
</script>
</body>
</html>

总结:

  1. 当一个form表单内包含submit按钮时,在某个input输入框内回车会触发表单提交,这非常方便,不需要我们针对每个输入框处理keydown事件了;
  2. 在submit按钮上绑定click事件和在form上绑定onsubmit事件是一模一样的效果,如果2个都是写了,则先触发click,后触发onsubmit;如果click里preventDefault()了,那么onsubmit不会执行。
  3. <input type="submit" value="提交"/><button type="submit">提交</button>都可以,button的type默认就是submit,但是部分浏览器默认值不是,所以为了兼容性,一般都会加上type;
  4. 还有<button type="reset"/>
  5. 默认情况下,表单提交后页面会刷新(通过action指定提交地址),所以我们一般提交表单时都是e.preventDefault()后自行实现提交逻辑;
  6. 无意中发现,onsubmit的方法名称不能是submit,否则无效;