Javascript性能? - 将事件放在html标签中,还是绑定它们? [英] Javascript performance ? - Put events in html tag, or bind them?

查看:146
本文介绍了Javascript性能? - 将事件放在html标签中,还是绑定它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪个是更好的性能...我有一个网络应用程序的事情。它有很多javascript。当单击按钮时,隐藏的div变得可见。这个新的div有5个按钮。哪个更好的表现:



1)将按钮点击事件放在每个按钮的html标签中,如onClick =alert('hey');
2.)当div可见时,将事件附加到每个按钮,然后在隐藏包含按钮的div时删除事件?



问是因为我想象的是,如果html标签中的事件不断存在,页面可能会陷入僵局。我认为页面可能会更快,只有当用户可以看到按钮点击它们时,才能看到这些事件。



任何帮助都很棒!谢谢!

解决方案

我会使用 事件委托



这样,您可以随意添加/删除任何按钮,而不用担心在每个按钮上附加事件。这种方法也是更有效的记忆,因为你总是有一个单一的事件处理程序,而不是直接在每个按钮上的N个。


I'm wondering which is better for performance... I have a "web app" sort of thing. It has a lot of javascript. When a button is clicked, a hidden div becomes visible. This new div has 5 buttons. Which is better for performance:

1.) put the button click events in the html tag of each button like onClick="alert('hey');" 2.) Attach events to each button when the div is visible, and then remove the events when I hide the div containing the buttons?

The reason I ask is because I imagine the page might get bogged down if the events in the html tags are constantly there. I figure the page might be faster to only have those events when the user can see the buttons to click them.

Any help is great! Thanks!

解决方案

I would use event delegation.

This way you can freely add/remove any buttons without worrying about attaching events on each one of them. This approach is also more memory efficient, since you always have one single event handler instead of N ones directly on each button.

这篇关于Javascript性能? - 将事件放在html标签中,还是绑定它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆