essay | tech | year-summary | about
日期:2018-09-09T00:00:00Z
nodejs学习中,碰到这样的一段有趣的代码。
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
$('form').submit(do_something);
我遇到了几个问题,我把解决他们的思路记录下来。
首先我疑惑的是,这个button上面也没有任何"submit"的标识,究竟为什么点回车or点那个button,就可以做do_something这个函数里面的东西?
我觉得这个太不科学了,这一点也不编程。
我开始在MDN的海洋中寻找。
终于让我找到这样的一句话。[1]
if there's only one <button> inside the <form>, that button will be treated as the "submit" button.
原来是只有一个button的话,那么就默认当作submit处理= =
这个确有点玄幻。毕竟不是一个好的习惯。
接下来我就产生了新的疑问。
这个东西如果不用jQuery应该怎么写。
那么首先问题来了,
我找到了这样的资料[6]:
jQuery certainly doesn’t help us here. The code follows the same intuitive syntax if we want to trigger some other DOM events, such as focus and blur, or submit on a <form>
也就是说,jQuery这里调用的其实是浏览器的API,用jQuery写不过是加了一层jQuery的皮,事实上是很没有效率。
不过事实上下面2种写法是错误的。
document.querySelector("form").submit()//wrong
或者像jQuery这种写法也不对。
document.querySelector("form").submit(you_function)//wrong
根据w3c的标准文档[5],form这个元素的submit是不可以像jQuery[4]一样拥有parameter的,然后我强行把submit重写似乎也不被允许 = = ||
让我缓一缓。(我缓了一个下午,在仔细的读各种文档)
最后在重读[2]的时候,里面有一句话引起了我的注意:
When invoking this method directly, no submit event is raised (in particular, the form's onsubmit event handler is not run), and constraint validation is not triggered either.
提醒了我,我应该写的是onsubmit()这个事件....
所以准确的写法是
document.querySelector("form").onsubmit = ur_function
var ur_function = () => {do_something; return false;}
这里的return false是防止页面刷新。
那么神奇的来了,
根据[7],这个疑似是历史遗留问题....我的天....
这个邮件中有这样的文字
submit
Submits the form. It performs the same action as a submit button.
I don't think the last sentence is correct. Using a submit input will
trigger onsubmit. The submit method will not.
by Filipus Klutiero
像使用jQuery的人也会有这个疑问[8]...
喔,这个锅,历史你背好了...
[1]MDN <input type="submit">
[2]MDN form.submit
[3]MDN <form>
[4]jQuery Doc .submit()
[5]W3 1. Document Object Model HTML
[6]You Don't Need jQuery!
[7]DOM Level 2 HTML: Note about onsubmit is misplaced in HTMLFormElement spec (in enctype attribute rather than in submit method) (was Re: Minor formatting error in HTMLFormElement spec)
[8]jQuery #3115 CLOSED BUG (WONTFIX)