代码之家  ›  专栏  ›  技术社区  ›  Jake

如果jQuery$('.class',context)与.class匹配,如何让它包含context本身?

  •  4
  • Jake  · 技术社区  · 15 年前

    我希望能够匹配给定上下文中的所有元素 包括…在内 上下文元素本身。
    这是我目前正在使用的代码,但它似乎效率低下。有更好的办法吗?

    var context = $('#id');   
    var filters = '.class1, .class2';
    
    // take context itself if it matches filters
    $(context).filter(filters)
    // add anything matching filters inside context
    .add($(filters, context))
    

    注: .add($(f,c)) 在jQ 1.3中作为 .add(f,c)

    2 回复  |  直到 15 年前
        1
  •  3
  •   Nick Craver    15 年前

    您可以这样做:

    $(context).find('*').andSelf().filter(filters)
    

    .andSelf() .andSelf()

    $(context).find(filters).andSelf(filters)
    

    但仍然没有很大的改善。

        2
  •  2
  •   Andrew    12 年前

    看来@Nick Craver的想法被推到了制作阶段。jQuery的 addBack() andSelf() 它接受一个选择器。

    $(context).find(filters).addBack(filters)