简体   繁体   中英

How to empty the <ul> in the nest <li> using jquery

I'm trying to create a menu and its sub menu, but receiving the data from database. And I created the menu successfully, this is my code :

 $(document).ready(function () {
    var url = '<%: Url.Content("~/") %>' + "Products/GetMenuList";
    $.getJSON(url, function (data) {
    var mainMenu = $("#content ul#navmenu-v");
        $.each(data, function (index, dataOption) { 
           var new_li = $("<li id='level1'><a href='javascript:void(0);' id='" 
                       + dataOption.ID + "' class ='selectedcategory'>" + 
                       dataOption.Name + "</a>");
        mainMenu.append(new_li);

    });
     $('.selectedcategory').mouseover(function () {
     $("ul#subCat").empty();
     $("li#level1").append("<ul id='subCat'>");
     var urlCat = '<%: Url.Content("~/") %>' + "Products/GetCategoryList";
        $.getJSON(urlCat, { Depid: this.id }, function (dataCat) {
           $.each(dataCat, function (indexCat, dataOptionCat) {
           $("ul#subCat").append("<li><a href='javascript:void(0);' 
              class='selectedsubcat' id='" + dataOptionCat.id + "'>" + 
                dataOptionCat.Name + "</a></li></ul></li>");
           });
       });
   }); 
  });
});

This is the HTML :

<div id="content">
 <ul id='navmenu-v'>
 </ul>
</div>

But it didn't get the right sub menu due to the main menu. Could anyone show me some suggestion please.

Thanks so much.

我认为你正在以错误的顺序关闭你的HTML,你正在关闭每个循环中的UI及其外部LI

Try this looks like what you want I hv simulated it here http://jsfiddle.net/d4udts/W9cCE/5/

$(document).ready(function () {


  var url = '<%: Url.Content("~/") %>' + "Products/GetMenuList";
  $.getJSON(url, function (data) {

    var mainMenu = $("#content ul#navmenu-v");
    $.each(data, function (index, dataOption) {
       var new_li = $("<li class='level1'><a href='javascript:void(0);' id='"+ dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
       mainMenu.append(new_li);

    });

    $('.level1').hover(function(){
       $(this).append("<ul class='subCat'></ul>");
       var ul=$(this).children('ul');

       var urlCat = '<%: Url.Content("~/") %>' + "Products/GetCategoryList";
       $.getJSON(urlCat, { Depid: $(this).find('a.selectedcategory').attr('id')}, function (dataCat) {

         $.each(dataCat, function (indexCat, dataOptionCat) {
           $(ul).append("<li><a href='javascript:void(0);'" +
           "class='selectedsubcat' id='" + dataOptionCat.id + "'>" +
            dataOptionCat.Name + "</a></li>");
          });
        });
      },function(){
      $(this).children('ul').remove();
    });
  }); 
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM