gpt4 book ai didi

javascript - 如何创建dl标签并在其中显示数据

转载 作者:行者123 更新时间:2023-11-30 20:34:50 25 4
gpt4 key购买 nike

我有一个 json 数据,我想在 dl 标签中显示它,我想在每次循环遍历 json 数据时创建新的 dl 标签,但我得到的输出是 dl 将在 dt 之前创建和关闭和 dd 应该是在它创建的内部,你可以在下面的 fiddle 中看到 jsfiddle.net/buo28k1L/56/ .下面是我的代码,我向 dl 添加了样式以显示 dl 的形成位置,您可以看到 dt 和 dd 在 dl 外部而不是在 dl 内部。

HTML

<div id="content"></div>

CSS

dl {
border:1px solid red;
height: 100px;
width: 300px;
}

JS

  var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]

if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];

for (var i = 0; i < firstdata.length; i++) {
// var d = $( document.createElement('dl') );
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");

for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}

最佳答案

您的第一个 for 循环中存在错误。试试这个。

for (var i = 0; i < firstdata.length; i++) {
// var d = $( document.createElement('dl') );
//create an empty dl tag
var dl = $("<dl></dl>");
//append your dt
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dt>");
//append your all dd
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" +secdata[i][j].name + "</dd>");
}
}
//append each dl before starting new one.
content.append(dl);
}

关于javascript - 如何创建dl标签并在其中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49953427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com