jQuery,如何使用多个缓存的元素 [英] jQuery, how to use multiple cached elements

查看:150
本文介绍了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():< a href =http://api.jquery.com/add =nofollow noreferrer> 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...)

这篇关于jQuery,如何使用多个缓存的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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