javascript - 被推送到数组的缓存选择器

标签 javascript jquery html performance

我的网站有很多 div:

var cubes = [];
var allCubes = '';
for(var i = 0; i < 857; i++) {
    var randomleft = Math.floor(Math.random()*1000),
        randomtop = Math.floor(Math.random()*1000);
    allCubes += '<div id="cube'+i+'" class="cube" style="position: absolute; left: '+randomleft+'px; top: '+randomtop+'px; width: 7px; height: 7px; z-index: -1"></div>';
}  

$('body').append(allCubes);

我想用 css3-transition 为每个 div 制作动画,因此我正在做另一个循环来为它们提供一个 ID。

for(var i = 0; i < 857; i++) { 
    cubes.push($('#cube'+i));   
}

但是如何缓存变量中的所有 $('#cubeX') 呢?难道不建议这样做吗,因为我用它做了很多动画。

干杯

最佳答案

如果您确实想缓存对象,在这种情况下您可以使用类似的对象

var cubes = {};
var allCubes = '';
for (var i = 0; i < 857; i++) {
    var randomleft = Math.floor(Math.random() * 1000),
        randomtop = Math.floor(Math.random() * 1000);
    allCubes += '<div id="cube' + i + '" class="cube" style="position: absolute; left: ' + randomleft + 'px; top: ' + randomtop + 'px; width: 7px; height: 7px; z-index: -1"></div>';
}

$('body').append(allCubes);
for (var i = 0; i < 857; i++) {
    cubes['cube' + i] = $('#cube' + i)
}

function getCube(index){
    var cube = cubes['cube' + index];
    if(!cube){
        cube = $('#cube' + index);
        cubes['cube' + index] = cube;
    }
    return cube;
}

//then you can access the cubes via
getCube(1)
getCube(2)
getCube(3)

关于javascript - 被推送到数组的缓存选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802870/

相关文章:

javascript - DOM 中 child 的深度

jquery - 如何让 Photoswipe 从缩略图列表中识别整个图库

javascript - 使用 jquery 根据下拉选择选择单选按钮

javascript - 完整日历到 Excel 和 .pdf

html - 如何获得 div 以便它始终到达底部?

javascript - React 防止全局样式影响组件

javascript - 为什么 localStorage ["..."] 未定义,但 localStorage.getItem ("...") 为空?

php - 多个输入字段上的 Jquery 日期选择器

html - 在负左值上调整元素位置

javascript - 根据 Bootstrap 中输入的内容动态重新排序列