jQuery,如何使用多个缓存的元素

问题描述:

对于我的项目,我使用缓存的选择器加快,并看到改进:
(减少文档内的搜索)

For my project I'm using cached selectors to speed up, and see improvements: (to reduce searches inside the document)

var sel1 = $('#selector1');
var sel2 = $('#selector2');

如何在这种情况下使用缓存的选择器?例如:

how can I use cached selectors in this situation? for ex:

$('#selector1, #selector2').fadeTo(300, 1, 'linear');

这只是为了擦亮我的代码

It's just to polish up my code

Ty:)

您可以使用 .add() 将元素添加到匹配元素集:

You can use .add() to "Add elements to the set of matched elements":

sel1.add(sel2).fadeTo(300, 1, 'linear');

文档 .add(): http://api.jquery.com/add

.add()可以输入:


  • li>
  • DOM元素

  • jQuery对象

  • 和具有上下文的选择器( $ ; selector>',< context>)

  • a selector
  • DOM elements
  • jQuery objects
  • and selectors with context ($('<selector>', <context>))

到jQuery:

var one = $('#one')[0],
    two = $('#two')[0];

$([one, two]).fadeTo(300, 1, 'linear');

这里是一个演示: http://jsfiddle.net/3xJzE/

UPDATE

我创建了一个jsperf的当前答案的三种不同的方法: http://jsperf.com/jquery-fadeto-once-vs-twice (似乎使用数组选择器是最快的: $([one,two]) .fadeTo ...

I created a jsperf of the three different methods that are currently answers: http://jsperf.com/jquery-fadeto-once-vs-twice (it seems like using an array selector is the fastest: $([one, two]).fadeTo...)