0

Possible Duplicate:
Merging jQuery objects


** The goal is performance. The duplicate question addresses the function, but I don't believe adds performance value and doesn't address that aspect. **

I want to chain several jQuery elements, for the sake of performance, but for optimization sake they're already cached in variables.

so if I have

$elem1 = $('div#elem1');
$elem2 = $('div#elem2');
$elem3 = $('div#elem3');

This doesn't work so well:

$elem1,$elem2,$elem3.hide(); 

Is there any way to do that, chaining with already cached elements?

Thanks!

[Edits]
Ok, I really need to clarify. My goal for chaining is performance, with the bonus of concise yet clear code.
$('div#elem1, div#elem2, div#elem3').hide();
defeats the point as it's no longer using the cached vars, but accessing the dom again. Accessing the dom is expensive, so i'm pretty sure it's slower than the 3 lines.
.add() and .merge(), I'm assuming are more expensive than seperating the operation on three lines. For performance sake, until I have time to jPerf, I'll assume 3 different lines rather than extra operations has the best performance.


Thanks for the collaboration, brainstorming, and thoughts, I do appreciate it. I wasn't aware of the possibilities and wouldn't have known what to test on jPerf otherwise.

4

4 回答 4

2

不确定它有多干净,但您可以使用 jQueryeach()来遍历它们的数组。它不完全是链接,但最终结果应该是相同的:

$.each([$elem1,$elem2,$elem3], function() {this.hide()})
于 2012-09-03T16:45:33.983 回答
1

我唯一能想到的就是把它们放在一起.add()

$elem1.add($elem2).add($elem3).hide();
于 2012-09-03T16:30:38.323 回答
0

不,我的朋友,这永远不会奏效。尝试这样做

$('div#elem1, div#elem2, div#elem3').hide();

或者

$elem1.hide(); $elem2.hide(); $elem3.hide()

于 2012-09-03T16:35:11.597 回答
0
var elements = [];
elements.push($elem1);
elements.push($elem2);
elements.push($elem3);

$(elements).each(function(i){
    elements[i].hide();
});
于 2012-09-03T16:37:40.467 回答