将 jQuery 事件绑定到元素的最佳方法是什么

发布于 2024-12-21 15:46:54 字数 242 浏览 0 评论 0原文

我目前正在一个拥有成千上万行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奶茶白久 2024-12-28 15:46:54

您应该将元素绑定到包含所有单击元素的最低 dom 元素。

因此,如果有一个名为 foo 的 div 包含每个元素,您会说:

$("#foo").on("click", "yourselector", function(){
});

如果您的元素分布在页面的每一英寸上,那么您会在最顶部监听:

$(document).on("click", "yourselector", function(){
});

如果我我正确理解你的问题,我真的希望以前的开发人员没有做类似的事情:

$("#someButtonId").on("click", function(){
    //this defeats the whole purpose of on!!!
});

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:

$("#foo").on("click", "yourselector", function(){
});

If the your elements are spread across every inch of your page, then you'd listen at the very top:

$(document).on("click", "yourselector", function(){
});

If I'm understanding your question correctly, I really really hope the previous developer didn't do something like:

$("#someButtonId").on("click", function(){
    //this defeats the whole purpose of on!!!
});
终陌 2024-12-28 15:46:54

您可以在一个元素上多次绑定同一事件,但如果同一链接上有多达 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文