Reputation: 331
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.
Upvotes: 0
Views: 72
Reputation: 388446
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);
Upvotes: 2