jQuery .on() 在事件委托中有多个选择器? [英] jQuery .on() with multiple selectors in event delegation?

查看:26
本文介绍了jQuery .on() 在事件委托中有多个选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 jQuery 1.7 中使用了 .on(),想知道是否可以一次为已注入页面的元素附加多个选择器.以前,我使用的是 live() - 但鉴于性能改进,我想迁移的原因很明显.

你能不能像这样使用.on():

$(document).on('click', '#selector1, #selector2, .class1', function () {//东西});

附加到文档有什么好处吗?

?

解决方案

  1. <块引用>

    你能以如下方式使用 .on():

    $(document).on('click', '#selector1, #selector2, .class1', function () {//东西});

    是的,可以.

  2. <块引用>

    鉴于性能改进,我想使用它而不是 live().

    与使用 live() 相比,使用该代码片段没有性能优势,因为 live() 本身将事件绑定到文档,在 jQuery 1.7 中,在幕后实时调用 on.

  3. <块引用>

    附加到文档有什么好处吗?

    绑定到document 的缺点是事件在处理之前必须遍历整个祖先列表;如 jQuery 文档中所指出的,这是可能的最慢路线.通过将处理程序附加到更接近事件源的元素,最好更快地处理事件.

I have using .on() in jQuery 1.7 and wondered whether it is possible to attach multiple selectors at a time for elements that have been injected onto a page. Previously, I was using live() - but it's obvious why I want to move given performance improvements.

Can you use .on() in the manner like:

$(document).on('click', '#selector1, #selector2, .class1', function () { 
     //stuff
});

And are there any benefits lost in attaching to document ?

?

解决方案

  1. Can you use .on() in the manner like:

    $(document).on('click', '#selector1, #selector2, .class1', function () { 
        //stuff
    });
    

    Yes, that will work.

  2. I want to use this instead of live() given performance improvements.

    There are no performance advantages of using that code snippet as opposed to using live(), as live() itself binds events to the document, and in jQuery 1.7, live calls on behind the scenes.

  3. And are there any benefits lost in attaching to document?

    The downside to binding to document is that the event must traverse the entire list of ancestors before it is handled; this, as pointed out in the jQuery documentation, is the slowest possible route. It will be better to handle to event sooner, by attaching the handler to an element closer to the source of the event.

这篇关于jQuery .on() 在事件委托中有多个选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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