jQuery:为什么要为仅引用一次的对象创建变量? [英] Jquery: Why create a variable for something you're only referencing once?
问题描述
对于这样的事情:
jQuery:
$(document).ready(function(){
var container = $('.rotate_container');
var images = container.find('img');
container.everyTime(10, function (){
images.each(function() {
container.animate({scrollTop: $(this).offset().top - 165}, 2000).delay(1000);
});
});
});
将变量设置为容器"和图像"有什么意义?如果它们每个都只使用一次,那将有什么帮助呢?
What's the point of making the variables "container" and "images"? If they're each only used once, how does that help anything at all?
谢谢.
推荐答案
如果您确定,只能在代码中访问一次元素,则不会当然可以缓存它.
If you, for sure, only access an element once in your code, it does not make sense to cache it of course.
缓存DOM elements
的原因是访问它们非常昂贵.
The reason for caching DOM elements
is that it's awful expensive to access them.
在 ECMAland 和 DOMland 之间交叉bridge
是最昂贵的部分.您确实可以将它与桥梁进行比较,每次过桥时,您都需要支付通行费.因此,将已保存过路费的东西保留在ECMAland中是很有意义的.每次需要时都不要过桥.
Crossing the bridge
between ECMAland and DOMland is the most expensive part. You really can compare it with a bridge, each time you cross it you have to pay a toll. So it makes sense to keep the stuff in ECMAland for which you already payed a toll. Do not cross the bridge each time you need it.
在这张照片中,您会发现没关系,只要您过桥一次即可.
And in this picture you'll notice that it does not matter, if you only cross the bridge once.
这篇关于jQuery:为什么要为仅引用一次的对象创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!