简体   繁体   English

Jquery On事件。 代表和速度问题

[英]Jquery On event. Delegate and speed issue

I'm using in my code few events like: 我在我的代码中使用了一些事件,例如:

$( "body" ).on( "click", '.editButton', clickFunction);

And it creates events for every element inside Body that has class .editButton. 它为Body内部具有类.editButton的每个元素创建事件。 I add this event to the Body element as i don't know where can I have this buttons in the code, sometimes i'm doing many ajax requests to different parts of the site and I want them all to fire clickFunction. 我将此事件添加到Body元素,因为我不知道我在哪里可以在代码中使用此按钮,有时我正在对网站的不同部分做很多ajax请求,我希望它们都能触发clickFunction。 What impact has this method to the general page speed? 这种方法对一般页面速度有什么影响? What if I have 5-6 such a delegate events. 如果我有5-6个这样的委托事件怎么办? I'm not sure how it works. 我不确定它是如何工作的。 If I add some new html elements via Ajax call to the page does the script search every Body element for .editButton element and creates click event for it? 如果我通过Ajax调用添加一些新的html元素,那么脚本会搜索.editButton元素的每个Body元素并为它创建click事件吗? And when I have few such events will it bo done like that few times? 当我几乎没有这样的事件时,它会像那几次一样完成吗? How fast is it? 它有多快? Is it something we must be concerned about? 这是我们必须关注的事情吗?

If I add some new html elements via Ajax call to the page does the script search every Body element for .editButton element and creates click event for it? 如果我通过Ajax调用添加一些新的html元素,那么脚本会搜索.editButton元素的每个Body元素并为它创建click事件吗?

Well, this is not quite how Event Delegation in JavaScript works. 嗯,这不是JavaScript中的事件委派的工作原理。 You attach the event handler only once to the parent node. 您只将事件处理程序附加到父节点一次。 In your case the body tag. 在你的情况下body标签。

Now when any event, anywhere, on any node happens, the event propagates up the DOM tree. 现在,当任何节点上的任何事件发生时,事件都会向上传播到DOM树。 (Event Bubbling). (事件冒泡)。 Once it hits an event handler, the target of the handler is checked and the callback function is executed with it. 一旦它命中了事件处理程序,就会检查处理程序的目标并使用它执行回调函数。

In your case, whenever the edit button is clicked, (or whatever button is clicked), the event travels up, to your body where you have a click handler. 在您的情况下,无论何时单击编辑按钮(或单击任何按钮),事件都会向上移动到您拥有click处理程序的正文。 It sees that the target is the .editButton and JS knows this is the target of your handler. 它看到目标是.editButton ,JS知道这是你的处理程序的目标。

As you can see, the only way your performance would degrade is when you have a dom tree that is too deep. 正如您所看到的,当您的dom树太深时,性能降低的唯一方法就是降级。 That is why its a good pratice to add the event handler to a common parent and always to the body or document that some use. 这就是为什么将事件处理程序添加到公共父级并始终添加到某些使用的body或文档的良好实践。

So adding more such buttons wont cause any increase in performance issues. 因此添加更多此类按钮不会导致性能问题的任何增加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM