如何在JavaScript变量中存储多个jQuery选择器? [英] How do I store multiple jQuery selectors in a javascript variable?
问题描述
很明显,如果多次使用jQuery选择器,最好将它们存储在变量中(不是如果只使用一次,则不是一个好主意).
Obviously it's a good idea to store jQuery selectors in variables if they are used more than once (not a good idea if used only once).
我的问题是,如何在一个变量中存储可互换使用的多个选择器.
My question is, how do you store multiple selectors, that are used interchangeably, in a variable.
例如,假设我选择了$('#object1, #object2)
,然后选择了$('#object1').我将如何创建一个可以与其他变量组合以创建多个选择器的变量.
For instance, let's say I select $('#object1, #object2)
, then later on I select `$('#object1'). How would I create a variable that can be combined with other variables to create multiple selectors.
如果我要这样写的话:
var object1 = "#object1";
var object2 = "#object2";
$(object1 + "," + object2);
我只会引用字符串#object1
,而不是实际的选择器.
I would only be referencing the string #object1
, and not the actual selector.
那么我如何在变量中存储多个选择器,以便它们可以互换使用?
So how do I store multiple selectors in variables, so they can be used interchangeably?
推荐答案
问题不是selector string
,问题是DOM元素的查询. 问题"的意思是,它很昂贵.这就是为什么您只应查询一个元素并存储对它的引用.
The problem is not the selector string
, the problem is the query of the DOM element. "Problem" means, it's expensive. That is why you should only query an element once and store a reference to it.
var object1 = $('#object1'),
object2 = $('#object2');
object1.some_method();
更新
关于您的评论:
jQuery提供了.add()
help 方法,该方法可以连接jQuery对象:>
jQuery offers the .add()
help method which allows to concat jQuery objects:
object1.add(object2).method();
这篇关于如何在JavaScript变量中存储多个jQuery选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!