I have a category list. I wish to toggle my each category items when a click is done on the respective category.
I did the below code. But when I click any of the category, all the category items are toggled. I think the problem is with my selector. What change I should do now.
<div class="nav">
<ul>
<li class="main_category">Category1</li>
<div class="sub_category" style="display: none;">
<ul>
<li>Item1</li>
<li>Item2</li>
</ul>
</div>
<li class="main_category">Category2</li>
<div class="sub_category" style="display: none;">
<ul>
<li>Item1</li>
<li>Item2</li>
</ul>
</div>
</ul>
</div>
$(document).ready(function() {
$("li.main_category").click(function() {
$(".sub_category").slideToggle();
});
});
If you do not want to change your HTML markup, (assuming the item will div will remain next to li):
$(document).ready(function() {
$("li.main_category").click(function() {
$(this).next().slideToggle();
});
});
But, I would suggest you to change your markup a little (because you don't need or may not want divs inside the list) so that it is cleaner:
<div class="nav">
<ul>
<li class="main_category">Category1
<ul style="display:none">
<li>Item1</li>
<li>Item2</li>
</ul>
</li>
<li class="main_category">Category2
<ul style="display:none">
<li>Item1</li>
<li>Item2</li>
</ul>
</li>
</ul>
</div>
And the script:
$(document).ready(function() {
$("li.main_category").click(function() {
$(this).children("ul").slideToggle();
});
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加