我的网站有很多 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/