这是从哪里来的
当我第一次学习jQuery时,我通常会附加以下事件:
$('.my-widget a').click(function() {
$(this).toggleClass('active');
});
在了解了更多关于 Select 器速度和事件委派的信息后,我在几个地方读到了"jQuery事件委派将使代码更快"所以我开始写这样的代码:
$('.my-widget').on('click','a',function() {
$(this).toggleClass('active');
});
这也是复制已弃用的.live()事件的行为的推荐方式.这对我来说很重要,因为我的很多站点一直在动态添加/删除小部件.不过,上面的行为并不完全像.live(),因为只有添加到现有容器‘.my-widget’中的元素才会获得该行为.如果我在代码运行后动态添加另一个HTML挡路,这些元素将不会获得绑定到它们的事件.如下所示:
setTimeout(function() {
$('body').append('<div class="my-widget"><a>Click does nothing</a></div>');
}, 1000);
What I want to achieve:
- 旧的行为.live()//表示将事件附加到尚未存在的元素
- the benefits of .on()
- 绑定事件的最快性能
- 管理事件的简单方法
我现在附上所有这样的事件:
$(document).on('click.my-widget-namespace', '.my-widget a', function() {
$(this).toggleClass('active');
});
Which seems to meet all my goals. (Yes it's slower in IE for some reason, no idea why?)
It's fast because only a single event is tied to a singular element and the secondary selector is only evaluated when the event occurs (please correct me if this is wrong here). The namespace is awesome since it makes it easier to toggle the event listener.
My Solution/Question
So I'm starting to think that jQuery events should always be bound to $(document).
Is there any reason why you would not want to do this?
Could this be considered a best practice? If not, why?
如果你读过这整件事,谢谢.我感谢任何/所有反馈/见解.
Assumptions:
- 使用支持
.on()
//至少1.7版的jQuery - 您希望将事件添加到动态添加的内容中
Readings/Examples: