How to clear <ul> in nest <li> using jquery

I am trying to create a menu and its submenu, but I am getting data from the 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 HTML:

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

      

But because of the main menu, it didn't get the correct submenu. Can anyone show me some suggestion please.

Many thanks.

+3


source to share


2 answers


Try it, it looks like you want me to hv simulate 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();
    });
  }); 
});

      

+1


source


I think you are closing your HTML in the wrong order, you are closing Ul and its outer LI inside every loop



+1


source







All Articles