[英]Which method of binding a javascript event with jquery's on is more performant?
Let's say you have a web page with forms, and you want to trigger a handler whenever one of those forms is submitted, or whenever a form that is added to the page at a later point in time is submitted. 假设您有一个包含表单的网页,并且想要在提交这些表单之一或在稍后的某个时间点提交添加到页面的表单时触发处理程序。 Which method is better:
哪种方法更好:
$('form').on('submit', handler);
or 要么
$(document).on('submit', 'form', handler);
It's not which is better, it's which is more suitable for your needs, both of the methods are good and have their usage. 这不是更好,它更适合您的需求,这两种方法都很好,并且都有它们的用途。
The first only listens to submits that occur inside of forms, the latter listens to all submits, wait for them to bubble to the document
, and then fire the handler
callback. 前者仅侦听表单内部发生的提交,后者侦听所有提交,等待它们冒泡到
document
,然后触发handler
回调。
Note that with onsubmit
, it doesn't have so much difference, as with mousemove
or click
which can occur on every place in the <body>
, submit only happens in <forms>
, but it bubbles all the way to the document. 请注意,使用
onsubmit
并没有太大的区别,就像发生在<body>
每个位置的mousemove
或click
,提交仅发生在<forms>
,但是一直到文档。
If you want it to apply to forms you will add to your page later dynamically, the latter is the only version that will work at all. 如果希望将其应用于表单,则稍后将动态添加到页面中,后者是唯一可以使用的版本。
(Honestly, unless your page has thousands of forms, the performance difference shouldn't matter much anyway) (老实说,除非您的页面有成千上万的表格,否则性能差异不会有太大关系)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.