我正在尝试从JSON获取列表项并使其成为菜单项。现在我正在获取菜单项,但无法按预期进行。我作为列表项得到的所有项。
-10
现在此代码输出如下。
<ul id="demo"></ul>
<script>
var text, i, j, t, x = "";
var text = dmAPI.getNavItems();
for (i in text) {
if (text[i].inNavigation === true ) {
x += '<li><a href="'+text[i].path+'">' + text[i].title + '</a>'
if ( 'subNav' in text[i] ) {
for (j in text[i].subNav) {
x+='<li class="submenuitem"><a href="'+text[i].subNav[j].path +'">' + text[i].subNav[j].title + '</a>'
for ( t in text[i].subNav[j].subNav) {
x+='<li class="sub_submenuitem"><a href="'+text[i].subNav[j].subNav[t].path +'">' + text[i].subNav[j].subNav[t].title + '</a></li>';
}
'</li>';
}
}
'</li>';
} //end if
}// end for
document.getElementById("demo").innerHTML = x;
<script>
但是我想要这样的输出.....
<ul id="demo">
<li><a href="#">New Page</a></li>
<li class="submenuitem"><a href="#">New Page</a></li>
<li class="sub_submenuitem"><a href="#">New Page</a></li>
<li class="sub_submenuitem"><a href="#">New Page</a></li>
<li><a href="#">Features</a></li>
</ul>
我该怎么做?
答案 0 :(得分:1)
使用下面的代码
<script>
var text, i, j, t, x = "";
var text = dmAPI.getNavItems();
for (i in text) {
if (text[i].inNavigation === true ) {
x += '<li><a href="'+text[i].path+'">' + text[i].title + '</a>'
x +='<ul>';
if ( 'subNav' in text[i] ) {
for (j in text[i].subNav) {
x+='<li class="submenuitem"><a href="'+text[i].subNav[j].path +'">' + text[i].subNav[j].title + '</a>'
for ( t in text[i].subNav[j].subNav) {
x+='<li class="sub_submenuitem"><a href="'+text[i].subNav[j].subNav[t].path +'">' + text[i].subNav[j].subNav[t].title + '</a></li>';
}
x+='</li>';
}
}
x +='</ul>';
x +='</li>';
} //end if
}// end for
document.getElementById("demo").innerHTML = x;
<script>
答案 1 :(得分:0)
只需在需要的地方添加内部ul元素
<ul id="demo"></ul>
<script>
var text, i, j, t, x = "";
var text = dmAPI.getNavItems();
for (i in text) {
if (text[i].inNavigation === true ) {
x += '<li><a href="'+text[i].path+'">' + text[i].title + '</a>'
if ( 'subNav' in text[i] ) {
for (j in text[i].subNav) {
x+='<li class="submenuitem"><a href="'+text[i].subNav[j].path +'">' +
text[i].subNav[j].title + '</a>'
for ( t in text[i].subNav[j].subNav) {
x+='<ul>' //<--this
x+='<li class="sub_submenuitem"><a href="'+text[i].subNav[j].subNav[t].path
+'">' + text[i].subNav[j].subNav[t].title + '</a></li>';
x+='</ul>' //<--and this
}
'</li>';
}
}
'</li>';
} //end if
}// end for
document.getElementById("demo").innerHTML = x;
<script>