[英]multilevel dropdown with javascript
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: 当我检查生成的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. 但是无论如何,您都不应该这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.