简体   繁体   English

让孩子在礼上

[英]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, 我有一个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, 没有附加li的对应关系,

$('.sub-cat-list1').append(sub_cat_li); is working, and it is appending all the sub_cat_li ul. 正在运行,并且正在附加所有sub_cat_li ul。 How get ul under the corresponding li. 如何在对应的li下获取ul。

The problem is parent_id is the anchor element which does not have the class .sub-cat-list1 . 问题是parent_id是不具有类.sub-cat-list1anchor元素。

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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