你如何缓存DOM元素? [英] How do you cache a DOM element?

查看:84
本文介绍了你如何缓存DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解反复引用 $('#Counter')是一个坏主意,因为你每次都跳进DOM。

I understand that referencing $('#Counter') over and over is a bad idea because you are "jumping into the DOM each time".

但是这更好吗?

Counter = $('#Counter');

然后在循环内:

Counter.val()++

编辑:

更正上面的代码段,应为:

Correction to the snippet above, which should be:

Counter.val(Counter.val()+1);

或者那是做同样的事情吗?

Or is that doing the same thing?

推荐答案

对于您所描述的情况,最好在输入迭代语句之前将jQuery对象保存在变量中,重复使用此对象。它将阻止在每次迭代时遍历DOM树。此外,按ID搜索可能不敏感,但按类名查询或使用复合选择器可能会充分降低性能。

For the case you described, it is preferrable to save jQuery object in a variable before entering the iteration statement, where you repeatedly use this object. It will prevent of traversing the DOM tree at each iteration. Besides it can be insensible for searching by ID, but querying by class name or using compound selectors may sufficiently decrease the performance.

var $Counter = $("#Counter");
for (...) {
    $Counter.val(function(i, val) { return +val + 1; });
    ...
}

注意使用函数作为<的参数code> val()在这种情况下更合理。

Pay attention to using function as argument of val() which is more reasonable in this case.

这篇关于你如何缓存DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆