javascript - 如何使用迭代嵌入列表
问题描述
这是一种通过迭代将列表嵌入列表(或您选择的任何 dom)中的方法。在我最初的调查中,我努力将 UL 插入现有的 LI。跳下去寻找答案。
原始问题:我正在尝试在列表中构建一个列表。虽然我可以成功构建父列表,但我没有成功注入子数组的迭代。
我有一个对象数组。这些对象内部可能有对象数组。例子:
[
{
id: "math",
students: [
{
id: "math student a"
},{
id: "math student b"
}
]},{
id: "sciences",
students: [
{
id: "sci student c"
},{
id: "sci student d",
award: [
{
id: "award a"
}, {
id: "award b"
}
]
}
]
}
]
我想迭代地建立一个学习区的列表,学习区内的学生,学生的成绩等等。这些是列表中的列表。
下面的解决方案
var data = [
{
id: "math",
students: [{ id: "math student a" }, { id: "math student b" }]
},
{
id: "sciences",
students: [
{ id: "sci student c" },
{ id: "sci student d", award: [{ id: "award a" }, { id: "award b" }] }
]
}
];
// global loops
function _listLoop(list, cb, res) {
if (!!!list) return;
var len = list.length;
var idx = 0;
while (idx < len) {
res = cb(list[idx], res, idx);
idx++;
}
return res;
}
var drawList = function (item, collection) {
for (var prop in item) {
value = item[prop];
if (Array.isArray(value)) {
var ul = document.createElement("ul");
var lastLi = collection.lastChild;
lastLi.appendChild( _listLoop(value, drawList, ul) )
} else {
var li = document.createElement("li");
li.textContent = value;
collection.appendChild( li )
}
}
return collection;
};
var ul = document.createElement( 'ul' );
var dom = _listLoop(data, drawList, ul);
var app = document.querySelector("#app");
app.appendChild(dom);
生成的 HTML 就是这样
<div id="app">
<ul>
<li>
math
<ul>
<li>math student a</li>
<li>math student b</li>
</ul>
</li>
<li>
sciences
<ul>
<li>sci student c</li>
<li>sci student d
<ul>
<li>award a</li>
<li>award b</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
解决方案
我也修改了原始问题以提供答案。
var data = [
{
id: "math",
students: [{ id: "math student a" }, { id: "math student b" }]
},
{
id: "sciences",
students: [
{ id: "sci student c" },
{ id: "sci student d", award: [{ id: "award a" }, { id: "award b" }] }
]
}
];
// global loops
function _listLoop(list, cb, res) {
if (!!!list) return;
var len = list.length;
var idx = 0;
while (idx < len) {
res = cb(list[idx], res, idx);
idx++;
}
return res;
}
var drawList = function (item, collection) {
for (var prop in item) {
value = item[prop];
if (Array.isArray(value)) {
var ul = document.createElement("ul");
var lastLi = collection.lastChild;
lastLi.appendChild( _listLoop(value, drawList, ul) )
} else {
var li = document.createElement("li");
li.textContent = value;
collection.appendChild( li )
}
}
return collection;
};
var ul = document.createElement( 'ul' );
var dom = _listLoop(data, drawList, ul);
var app = document.querySelector("#app");
app.appendChild(dom);