找到你要的答案

Q:Jquery selector performance & behavior [duplicate]

Q:jQuery选择器的性能和行为[复制]

This question already has an answer here:

I have a strange question about jquery selector behavior.

First approach:

$('#div').find('#something').html('hahah');
$('#div').find('#something').html('hahah');
$('#div').show();

Second approach:

var $div = $('#div');
$div.find('#something').html('hahah');
$div.find('#something').html('hahah');
$div.show();

I know that it might not have too much difference, but is the second faster than the first?? I've always used the second approach but I'm not sure if there is a difference because I don't know how the jquery selector algorithm works.

这个问题在这里已经有了答案:

我有一个关于jQuery选择器行为奇怪的问题。

第一种方法:

$('#div').find('#something').html('hahah');
$('#div').find('#something').html('hahah');
$('#div').show();

第二方法:

var $div = $('#div');
$div.find('#something').html('hahah');
$div.find('#something').html('hahah');
$div.show();

我知道它可能没有太大的区别,但第二快比第一??我一直用第二种方法,但是我不确定是否有差异,因为我不知道jQuery选择器算法。

answer1: 回答1:

The second way is faster/better because you have cached the selector.

Everytime you call $('selector'), the jQuery selector engine(sizzle) is called to locate your desired elements.

However, when you store them in a variable, you do not need to repeatedly call the selector engine as the results are stored.

Note, in your example above, caching can be further improved by storing the find() result as well

var $something = $('#div').find('#something');
$something.html('hahah');
$something.html('hahah');
$something.show();

第二种方法是更快/更好,因为你已经缓存选择器。

每次你打电话给$('selector '),jQuery的选择器引擎(啸)来找到你的所需的元素。

但是,当将它们存储在变量中时,则不必在结果存储时重复调用选择器引擎。

请注意,在你的例子中,缓存可以存储()的结果进一步改进

var $something = $('#div').find('#something');
$something.html('hahah');
$something.html('hahah');
$something.show();
javascript  jquery