jquery的对象未定义
问题描述:
我创建随机的div的负载和将它们附加到体:jquery的对象未定义
var cubes = [],
allCubes = ''
for(var i = 0; i < 150; i++) {
var randomleft = Math.floor(Math.random()*1000),
randomtop = Math.floor(Math.random()*1000);
allCubes += '<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>';
cubes.push($('#cube'+i));
}
$('body').append(allCubes);
以后然后我想选择一个特定的数组元素(其是jquery的对象作为上方观察)在点击处理程序中:
$('#trigger').click(function() {
console.log(cubes[1].attr('id'));
});
而且我把我扔到undefined
。为什么?
答
因为要附加的元素只是后来的时间点,你正在创建之前,与该会没有取(因为该元素是尚未DOM)选择一个jQuery对象。相反,只需将该ID保存在数组中并稍后构建该对象。
var cubes = [],
allCubes = ''
for(var i = 0; i < 150; i++) {
var randomleft = Math.floor(Math.random()*1000),
randomtop = Math.floor(Math.random()*1000);
allCubes += '<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>';
cubes.push('#cube'+i); //just save the id
}
$('body').append(allCubes);
和
$('#trigger').click(function() {
console.log(cubes[1]);
//create object as
var $cube = $(cubes[1]);
});
或做:
var cubes = [];
for(var i = 0; i < 150; i++) {
var randomleft = Math.floor(Math.random()*1000),
randomtop = Math.floor(Math.random()*1000);
cubes.push($('<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>'));
}
$('body').append(cubes);
和
$('#trigger').click(function() {
console.log(cubes[1].attr('id'));
});
答
PSL是正确的。或者只是追加代码每次
randomtop = Math.floor(Math.random()*1000);
$('body').append('<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>');
cubes.push($('#cube'+i));
+0
否否。最好在最后附加到DOM,而不是在每次迭代期间。 – PSL
答
您要创建:
cubes.push($('#cube'+i));
前#cubeX
产品的DOM,所以你创建了jQuery对象,并把你的数组中有任何操作,因为它在创建jQuery对象时在DOM中找不到#cubeX
。
我建议你把添加的项的公共类,并改变你的代码如下:
allCubes = ''
for(var i = 0; i < 150; i++) {
var randomleft = Math.floor(Math.random()*1000),
randomtop = Math.floor(Math.random()*1000);
allCubes += '<div id="cube'+ i + '" class="cube" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>';
}
$('body').append(allCubes);
然后,每当你想获得的所有立方体的项目,你可以使用这个:
$(".cube")
,你并不需要它们永久地存储在阵列中。只需在需要时提取它们。
如果你想关闭第二个属性,你可以这样做:
$('#trigger').click(function() {
console.log($(".cube").eq(1).attr('id'));
});
是的,这就是它!非常感谢你:) – supersize
但它不是性能较差? – supersize
@supersize是的,因为你每次点击时都会创建它,如果不是你可以做的就是获得所有的多维数据集......使用开始于选择器。 – PSL