我试图动态地创建显示用于阵列中的所有对象的每个对象值的DOM元素。
我用一个循环营造的元素,并试图版本的内容匹配到阵列的迭代,但它不工作。下面是我的代码(这是一个简化版本,以获得该代码工作)。
let divTwo = document.querySelector('.div-two');
let bigArray = [{
first: 'Joe',
location: 'Washington'
},
{
first: 'Jon',
location: 'Boston'
},
{
first: 'Brian',
location: 'New York'
},
];
let smallArray = ['first', 'location'];
function addNames() {
for (let i = 0; i < bigArray.length; i++) {
for (let j = 0; j < smallArray.length; j++) {
let newSpan = document.createElement('span');
newSpan.id = 'spanny' + (j + 1);
divTwo.appendChild(newSpan);
document.getElementById('spanny1').textContent = bigArray[j].first;
document.getElementById('spanny2').textContent = bigArray[j].location;
// newSpan[0].textContent = bigArray[0].first; *also doesn’t work*
// newSpan[1].textContent = bigArray[0].location; *also doesn’t work*
}
}
}
addNames();
你真的不希望这些ID添加到<span>
s,因为它们将出现三次,每次你的页面,这是无效的。
你可能在寻找这样的事情。你想获得i
的bigArray
个元素,然后得到与在j
的smallArray
个元素给出的键关联的值。因此,使用bigArray[i][smallArray[j]]
。
function addNames() {
for (let i = 0; i < bigArray.length; i++) {
for (let j = 0; j < smallArray.length; j++) {
let newSpan = document.createElement("span");
divTwo.appendChild(newSpan);
newSpan.textContent = bigArray[i][smallArray[j]];
}
}
}
它的清洁使用ECMAScript 6+:
function addNames() {
bigArray.forEach((data) => divTwo.append(...smallArray.map((key) => Object.assign(document.createElement("span"), {
textContent: data[key]
}))));
}