我已经嵌套了包含儿童的无序列表,我试图将列表中的所有数据存储到JSON格式数据中:
以下是我的HTML代码:
<nav id="nav">
<ul class="header-top-nav">
<li>
<a href="index.html">Home</a>
<ul>
<li><a href="subhome1.html">Home 1</a>
<ul>
<li><a href="subsubhome1.html">Sub Home</a></li>
</ul>
</li>
<li><a href="subhome2.html">Home 2</a></li>
<li><a href="subhome3.html">Home 3</a></li>
</ul>
</li>
</ul>
</nav>
我的JQuery:
content = [];
$('nav > ul').find('li').each( function () {
pages = {};
function menu() {
pages['pagelink'] = $(this).children('a').attr('href');
pages['pagename'] = $(this).children('a').text();
var submenucheck = $(this).children('ul').length;
if(submenucheck){
pages['submenu'] = [];
menu();
}
else{
pages['submenu'] = "NULL";
}
contents.push(pages);
}menu();
});
我希望数据格式如下:
{
"pages": [
{
"pagelink": "index.html",
"pagename": "Home",
"submenu": [
{
"pagelink": "subhome1.html",
"pagename": "Home 1",
"submenu": [
{
"pagelink": "subsubhome1.html",
"pagename": "Sub Home",
"submenu": "NULL"
}
]
},
{
"pagelink": "subhome2.html",
"pagename": "Home 2",
"submenu": "NULL"
},
{
"pagelink": "subhome3.html",
"pagename": "Home 3",
"submenu": "NULL"
}
]
}
]
}
请帮助我实现这一目标。