简体   繁体   English

哪种将javascript事件与jquery绑定在一起的方法性能更高?

[英]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>每个位置的mousemoveclick ,提交仅发生在<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.

相关问题 哪种方法在使用jQuery创建更深层的嵌套节点以及属性时性能更高? - Which method is more performant for creating deeper nesting nodes along with the attributes using jQuery? jQuery`on`方法未绑定事件 - jQuery `on` method is not binding event 哪个性能更高:jQuery.live(),还是内联 onevent 属性? - Which is more performant: jQuery.live(), or inline onevent attributes? 在 Javascript/jQuery 中运行函数之前检查元素是否存在是否更高效? - Is it more performant to check if element exists before running functions in Javascript/jQuery? Mootools选择器$或$$。 哪个表现更好 - Mootools Selectors $ or $$. Which is more performant 绑定JavaScript的oninput事件的最佳jQuery插件实现 - Best jQuery plugin implementation for binding JavaScript's oninput event 事件绑定 - jQuery与Javascript - Event Binding - jQuery vs Javascript 使用CSS或javascript / jQuery,我将使用哪种方法使网站的导航栏看起来更逼真3D? - using CSS or javascript/jQuery, which method would I use to make my site's nav bar look more 3d-ish? 哪个性能更好,<video> 或者<canvas>视频嵌入? - which is more performant, <video> or <canvas> with video embed? 哪个性能更高:XmlHttpRequest响应为HTML还是JSON? - Which is more performant: XmlHttpRequest response as HTML or JSON?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM