I am trying to create a dynamic multilevel dropdown with the following format:
<li><a href="catID">CatName A</a>
<ul class="dropdown-menu" id="CatNameA">
<li><a href="subcatID">subCatName AA</a></li>
<li><a href="subcatID">subCatName AB</a></li>
</ul>
</li>(iterated with diff values about a dozen times.)
My code:
$.each(data.cat, function (i, item) {
console.log(item.catID + " " + item.catName);
$("#divCategory").append('<li id='+item.catName+'><a href=/Category/GetCategory?_cat=' + item.catID + '>' + item.catName + '</a>');
if(item.subCat.length > 0)
{
$("#"+item.catName).append('<ul class="dropdown-menu">');
$.each(item.subCat, function (j, itemsub) {
console.log(itemsub.SubCatID + " " + itemsub.SubCatName);
$("#" + item.catName).append('<li><a href=/Category/GetSubcategory?_subcat=' + itemsub.SubCatID + '>' + itemsub.SubCatName + '</a></li>');
})
$("#" + item.catName + "li:last").append('</ul></li>');
} else {
$("#divCategory").append('</li>');
}
})
With the code above, when I check it seems that this line is not working properly:
$("#" + item.catName + "li:last").append('</ul></li>');
When I check the generated HTML:
<li><a href="catID">CatName A</a>
<ul class="dropdown-menu"> </ul> --> the closing UL is at the wrong spot.
<li><a href="subcatID">subCatName AA</a></li>
<li><a href="subcatID">subCatName AB</a></li>
</li>
Any help is much appreciated!
When you creating an element, use also end tag like this:
$("#"+item.catName).append('<ul class="dropdown-menu"></ul>');
Then, you do not need to append end tags later, new child elements will be place into created element.
Anyway, your selector is probaly wrong, because it should be:
$("#" + item.catName).append('</ul></li>');
But anyway you should not do it in this way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.