我正在尝试附加之前附加的HTML。就像首先添加密钥,然后将另一个添加到该密钥一样。
我的目标是创建嵌套的DOM。
这里是样本
let result = [
{
"name":"Component Murah",
"slug":"components-component-murah-34",
"id":34,
"parent":1
},
{
"name":"Gadget Case",
"slug":"components-component-murah-gadget-case-35",
"id":35,
"parent":34
},
{
"name":"Components",
"slug":"components-1",
"id":1,
"parent":false
},
];
$.each(result, function(i, field) {
if (field['parent'] == false){
$(`ul[class=nav-categories]`).append(
`<li class='child-${field['id']}'>
<a href='/shop/category/${field['slug']}'>
<span>${field['name']}</span>
</a>
</li>`);
}
$.each(result, function(i, field){
if (field['parent'] != false){
$(`li[class=child-${field['parent']}]`).append(
`<li class='child-${field['id']}'>
<a href='/shop/category/${field['slug']}'>
<span>${field['name']}</span>
</a>
</li>`);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav-categories">
</ul>
第一个也工作,第二个发现父母不工作?...
谢谢!
答案 0 :(得分:0)
我认为您忘记关闭第一个$ .each ....检查此示例
var res = [
{
"name":"Component Murah",
"slug":"components-component-murah-34",
"id":34,
"parent":1
},
{
"name":"Gadget Case",
"slug":"components-component-murah-gadget-case-35",
"id":35,
"parent":34
},
{
"name":"Components",
"slug":"components-1",
"id":1,
"parent":false
},
]
$.each(res, function(i, field){
if (field['parent'] == false){
$(`ul[class=nav-categories]`).append(
`<li class='child-` + field['id'] + `'>
<a href='/shop/category/` + field['slug'] + `'>
<span>` + field['name'] + `</span>
</a>
</li>`);
}
});
$.each(res, function(i, field){
if (field['parent'] != false){
$(`li[class=child-` + field['parent'] + `]`).append(
`<li class='child-` + field['id'] + `'>
<a href='/shop/category/` + field['slug'] + `'>
<span>` + field['name'] + `</span>
</a>
</li>`);
}
});
答案 1 :(得分:0)
检查此样本。它对您的代码进行了一些改进(例如正确使用反向刻度)
let result = [
{
"name":"Component Murah",
"slug":"components-component-murah-34",
"id":34,
"parent":1
},
{
"name":"Gadget Case",
"slug":"components-component-murah-gadget-case-35",
"id":35,
"parent":34
},
{
"name":"Components",
"slug":"components-1",
"id":1,
"parent":false
},
];
$.each(result, function(i, field) {
if (field['parent'] == false){
$(`ul[class=nav-categories]`).append(
`<li class='child-${field['id']}'>
<a href='/shop/category/${field['slug']}'>
<span>${field['name']}</span>
</a>
</li>`);
}
});
$.each(result, function(i, field){
if (field['parent'] != false){
$(`li[class=child-${field['parent']}]`).append(
`<li class='child-${field['id']}'>
<a href='/shop/category/${field['slug']}'>
<span>${field['name']}</span>
</a>
</li>`);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav-categories">
</ul>