将 jQuery 事件绑定到元素的最佳方法是什么
我目前正在一个拥有成千上万行 jQuery 代码的网站上工作,特别是有很多点击事件,我想知道是否有一种更具性能意识的最佳实践来将点击事件或任何事件绑定到一个项目。
当然,在各种链接和项目上拥有 30 多个点击事件,注册起来不会有良好的性能。正在使用新的 jQuery 1.7“on”函数,也许事件应该绑定到 body 元素或其他东西,然后检查将获取被单击的项目,然后从那里开始工作?或者这不是问题,并且绑定很多事件对于现代浏览器或性能来说并不是真正的问题?
I am currently working on a site that has thousands upon thousands of lines of jQuery code, there are a lot of click events especially and I was wondering is there a more performance-aware, best practice out there for binding click events or any event to an item.
Surely having 30+ click events on various links and items cannot be good performance wise being registered. The new jQuery 1.7 "on" function is being used, should perhaps the events be bound to the body element or something and then a check will get the item being clicked and then work from there? Or is it a non-issue and binding a lot of events not really an issue for a modern browser or performance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将元素绑定到包含所有单击元素的最低 dom 元素。
因此,如果有一个名为
foo
的 div 包含每个元素,您会说:如果您的元素分布在页面的每一英寸上,那么您会在最顶部监听:
如果我我正确理解你的问题,我真的希望以前的开发人员没有做类似的事情:
You should bind the elements to the lowest dom element that contains all of the clicked elements.
So if there's a div called
foo
that contains every single element, you'd say:If the your elements are spread across every inch of your page, then you'd listen at the very top:
If I'm understanding your question correctly, I really really hope the previous developer didn't do something like:
您可以在一个元素上多次绑定同一事件,但如果同一链接上有多达 30 个点击事件,则应该采用不同的方式。将您想要执行的所有不同操作的代码放在单个事件处理程序中,而不是单独绑定每个小事情。
You can bind the same event more than once on an element, but if you are having as much as 30 click events on the same link, you should do it differently. Put the code for all those different actions that you want to do in a single event handler instead of binding every little thing by themselves.