简体   繁体   中英

Getting Child ul in an li

I have a razor view, like

 <ul class="nav" id="product-cat-menu">
    @foreach (var category in ViewBag.CategoryList)
     {
       <li>
         <a href="#" id="@category.Id" class="parent-cat"><i class="fa fa-th-large"></i>@category.Name</a>
         <ul class="sub-cat-list1"></ul>
       </li>
     }
  </ul>   

and i have a jquery,

$("a.parent-cat").click(function () {
    var prent_id = this.id;

    $.getJSON('/Products/GetChildCategories/' + prent_id, function (data) {
        $.each(data, function (i, item) {
            var sub_cat_li = "<li><a href='#' id=" + JSON.stringify(item.Item1).replace(/\"/g, "") + ">" + JSON.stringify(item.Item2).replace(/\"/g, "") + "</li>";
            $('#' + prent_id + '.sub-cat-list1').append(sub_cat_li);    // this is not appending.            
        });

    });

});

$('#' + prent_id + '.sub-cat-list1').append(sub_cat_li); is not append the correspondi ul of the li,

$('.sub-cat-list1').append(sub_cat_li); is working, and it is appending all the sub_cat_li ul. How get ul under the corresponding li.

The problem is parent_id is the anchor element which does not have the class .sub-cat-list1 .

You can target the next sibling of the clicked anchor element like

$("a.parent-cat").click(function () {
    var $this = $(this);
    var prent_id = this.id;

    $.getJSON('/Products/GetChildCategories/' + prent_id, function (data) {
        $.each(data, function (i, item) {
            var sub_cat_li = "<li><a href='#' id=" + JSON.stringify(item.Item1).replace(/\"/g, "") + ">" + JSON.stringify(item.Item2).replace(/\"/g, "") + "</li>";
            $this.next('.sub-cat-list1').append(sub_cat_li); // this is not appending.            
        });

    });

});

Or use the adjacent sibling selector

$('#' + prent_id + ' + .sub-cat-list1').append(sub_cat_li); 

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