大桌子上有很多事件,使用事件冒泡是否更有效? [英] large table with lots of events, is using event bubbling more effecient?

查看:79
本文介绍了大桌子上有很多事件,使用事件冒泡是否更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的表/网格,每行都有事件,表头等.

I have a large table/grid that has events on each row, table headers, etc.

与其生成事件或将事件绑定到每个单元格,不如放置全局"事件会更好,然后我相信当发生单击或鼠标悬停事件时,它将整体上冒泡到我的全局"事件表,然后过滤事件调用者并做出反应.

Instead of me generating events or binding events to each cell, would it be better to put a 'global' event and then I believe when clicked or mouseover events occur, it will bubble up to my 'global' event on the entire table and then I get filter the event caller and react.

我之前已经阅读过有关此内容的信息,但不确定我的想法是否正确.

I've read about this before, but not sure if I have the idea correct.

这种方法有什么陷阱吗?

Are there any gotcha's with this approach?

推荐答案

是的,您的想法正确,是的,这样更好.使用jQuery,就像直接绑定事件一样简单-查找.delegate()方法.您可以做的是将事件处理程序放置在容器元素上,并告诉它如何基于普通的jQuery选择器将事件路由到处理程序,以过滤实际的事件目标.

Yes you've got the idea right, and yes it's better. With jQuery it's just as easy as binding the events directly - look up the .delegate() method. What that lets you do is place an event handler on a container element, and tell it how to route events to handlers based on an ordinary jQuery selector to filter the actual event targets.

因此:

$('#container').delegate('td.clickMe', 'click', function(e) {
  /* table cell click */
});

这篇关于大桌子上有很多事件,使用事件冒泡是否更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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