我有这个 JSON 文件:
{
"clubs": [
{
"name": "Feyenoord Rotterdam",
"origin": "Zuid-Holland",
"championships": "15"
},
{
"name": "Sparta Rotterdam",
"origin": "Zuid-Holland",
"championships": "6"
},
{
"name": "AZ Alkmaar",
"origin": "Noord-Holland",
"championships": "2"
},
{
"name": "Willem II",
"origin": "Noord-Brabant",
"championships": "3"
},
{
"name": "PSV Eindhoven",
"origin": "Noord-Brabant",
"championships": "24"
}
]
}
我想将每个俱乐部的数据(名称、起源、冠军)放在单独的 div 中。我正在尝试用 ES6 来做到这一点。 这是我现在的代码:
{
const createDiv = clubs => {
const $div = document.createElement(`div`);
$div.classList.add(`club-info`);
document.querySelector(`.clubs`).appendChild($div);
const $club = document.createElement(`p`);
$club.classList.add(`.clubname`);
$club.textContent = `${clubs.name}`;
const $origin = document.createElement(`p`);
$origin.classList.add(`.origin`);
$origin.textContent = `${clubs.origin}`;
const $championships = document.createElement(`p`);
$championships.classList.add(`.championships`);
$championships.textContent = `${clubs.championships}`;
document.querySelector(`.club-info`).appendChild($club);
document.querySelector(`.club-info`).appendChild($origin);
document.querySelector(`.club-info`).appendChild($championships);
};
const makeDivs = clubs => {
clubs.forEach(club => {
createDiv(club);
});
};
const parse = clubs => {
makeDivs(clubs);
};
const init = () => {
const url = `./assets/data/data.json`;
fetch(url)
.then(r => r.json())
.then(json => parse(json.clubs));
};
init();
}
现在的问题是,我有 5 个不同的 div,其类为“club-info”,但所有数据都转到第一个 div,如图所示。
最佳答案
当你这样做时
document.querySelector(`.club-info`).appendChild($club);
document.querySelector(`.club-info`).appendChild($origin);
document.querySelector(`.club-info`).appendChild($championships);
,它每次都会查找第一个 .club-info
元素。它不知道您想要使用也存储在 $div
中的元素。
由于 $div
包含当前的 .club-info
元素,因此您可以改用该变量:
$div.appendChild($club);
$div.appendChild($origin);
$div.appendChild($championships);
关于javascript - (ES6) 从 JSON 到 HTML 的数据(div),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50741163/