<li >
<button >item 1 </button>
<ul >
<li> sub item 1</li>
<li> sub item 2</li>
<li> sub item 3</li>
<li> sub item 4</li>
</ul>
</li>
<li >
<button >item 2 </button>
<ul >
<li> sub item 1</li>
<li> sub item 2</li>
<li> sub item 3</li>
<li> sub item 4</li>
</ul>
</li>
This li item is generated dynamically I want to toggle li on the cate-label button click. for that, I did the following code
$(document).on("click", "#categoryList > li .cate-label", function () {
var currentItem = $(this).closest("li");
ItemToHide = $("#categoryList > li").not(currentItem);
ItemToHide.removeClass("active-item");
ItemToHide.find(".sub-cate").hide();
currentItem.toggleClass("active-item");
}
);
when I try to hide item using ItemToHide.find(".sub-cate").hide(); it didn't hide anything . I tried to find the length of the item using ItemToHide.find(".sub-cate").length but it returned 0.
CodePudding user response:
Lower your event handling to something closer. I wrapped everything in a <menu>
tag and registered the click event to it instead of document
. It doesn't make much of a difference performance wise but I suggest it because it's looks as if your perspective is skewed if dealing with a larger view of the DOM and you'll be error prone:
var currentItem = $(this).closest("li");
ItemToHide = $("#categoryList > li").not(currentItem);
ItemToHide.removeClass("active-item");
ItemToHide.find(".sub-cate").hide();
currentItem.toggleClass("active-item");
That nightmare is now:
$(this).next('.sub-categ').toggle('ease-out');
$('menu').on("click", ".cate-label", toggleList);
function toggleList(e) {
$(this).next('.sub-categ').toggle('ease-out');
};
<menu>
<li >
<button >item 1 </button>
<ul >
<li> sub item 1</li>
<li> sub item 2</li>
<li> sub item 3</li>
<li> sub item 4</li>
</ul>
</li>
<li >
<button >item 2 </button>
<ul >
<li> sub item 1</li>
<li> sub item 2</li>
<li> sub item 3</li>
<li> sub item 4</li>
</ul>
</li>
</menu>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
Actually, the name of the class is not correct. Should be 'sub-cate'
, not 'sub-categ'
.
$(document).on("click", "#categoryList > li .cate-label", function () {
var currentItem = $(this).closest("li");
ItemToHide = $("#categoryList > li").not(currentItem);
ItemToHide.removeClass("active-item");
ItemToHide.find(".sub-cate").hide();
currentItem.toggleClass("active-item");
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div id="categoryList">
<li >
<button >item 1 </button>
<ul ><!--rename the class name-->
<li> sub item 1</li>
<li> sub item 2</li>
<li> sub item 3</li>
<li> sub item 4</li>
</ul>
</li>
<li >
<button >item 2 </button>
<ul ><!--rename the class name-->
<li> sub item 1</li>
<li> sub item 2</li>
<li> sub item 3</li>
<li> sub item 4</li>
</ul>
</li>
</div>