本文介绍了最有效的方式来重用jQuery选择的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以想象这个基于理论的正确答案,但我只是寻找一些确认。我想知道什么是最有效的方式来重用jQuery选择的元素是。例如:

I can imagine the correct answer to this based on theory, but I'm just looking for some confirmation. I'm wondering what the most efficient way to re-use a jQuery-selected element is. For example:

$('#my_div').css('background','red');
//some other code
$('#my_div').attr('name','Red Div');

vs。

myDiv = $('#my_div');
myDiv.css('background','red');
//some other code
myDiv.attr('name','Red Div');

我假设第二个例子更有效率,因为元素#my_div不必找到更多比一次。这是正确的吗?

I assume the second example is more efficient because the element #my_div doesn't have to get found more than once. Is that correct?

同样,首先将$(this)保存在varaible(如obj)中,然后重用obj使用$(this)一遍又一遍?在这种情况下,jQuery不是被迫重复寻找一个元素,但它被迫将它转换为一个jQuery对象[$(this)]。所以作为一般的经验法则,如果一个jQuery对象将被存储在一个变量,如果它将被使用一次以上?

Similarly, is it more efficient to first save $(this) in a varaible, such as 'obj', and then reuse 'obj' rather than using $(this) over and over? In this case, jQuery isn't being forced to find an element over and over again, but it IS being forced to convert this to a jQuery object [$(this)]. So as a general rule of thumb, should a jQuery object ALWAYS be stored in a variable if it will be used more than once?

推荐答案

如果你使用jQuery选择器( like $('#element')),那么你应该总是存储你的结果。

if you're using jQuery selector (like $('#element')), then yes, you should always store your results.

如果你使用对象并将它包装在jQuery中(例如 $(this)),就不必要了,因为jQuery不需要再次搜索该元素。

if you're using object and wrapping it in jQuery (like $(this)), it's not necessary, because jQuery doesn't need to search for that element again.

这篇关于最有效的方式来重用jQuery选择的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:55
查看更多