嗨,我正在尝试在for循环中创建多个div,但结果仅为1 div。我究竟做错了什么?
码:
for (var i = 0; i < $hubbe.colors.length; i++) {
$hubbe.pallet = document.createElement('DIV');
$hubbe.pallet.setAttribute('class', 'pallet');
$hubbe.toolbarLeft.appendChild($hubbe.pallet);
$hubbe.pallet.style.backgroundColor = $hubbe.colors[i];
Object.assign($hubbe.pallet.style, {
width: '40px',
height: '40px',
border: '2px solid #2c3e50',
margin: '20px 0 0 5px',
disaply: 'block',
cursor: 'pointer',
});
}
最佳答案
根据您告诉我的内容,我认为这可以解决您的问题。它将$hubbe.pallet
更改为数组,因此其余代码也可以正常工作:
$hubbe.pallet = []; //declares the array
for (var i = 0; i < $hubbe.colors.length; i++) {
var temp = document.createElement('DIV'); //create temp variable to work with
temp.setAttribute('class', 'pallet');
temp.style.backgroundColor = $hubbe.colors[i];
Object.assign(temp.style, {
width: '40px',
height: '40px',
border: '2px solid #2c3e50',
margin: '20px 0 0 5px',
disaply: 'block',
cursor: 'pointer',
});
$hubbe.toolbarLeft.appendChild(temp);
$hubbe.pallet[i] = temp; //adds the object to the array
}