开发者

jquery child selector problems

开发者 https://www.devze.com 2022-12-26 13:26 出处:网络
I have a basic website nav layout that looks like this: <li class=\"folder parent_folder\"> <a href=\"#\">Some Folder</a>

I have a basic website nav layout that looks like this:

    <li class="folder parent_folder">
<a href="#">Some Folder</a>
<ul class="submenu">
    <li class="file"><a href="#">An awesome file</a></li>
    <li class="file"><a href="#">An a开发者_C百科wesome file</a></li>
    <li class="file"><a href="#">An awesome file</a></li>
    <li class="file"><a href="#">An awesome file</a></li>
    <li class="file"><a href="#">An awesome file</a></li>
    <li class="file"><a href="#">An awesome file</a></li>
</ul>

I have several of these throughout the site's page. Using jquery, I'm trying to make it so that when you click "li.parent_folder" "ul.submenu" disappears and then reappears when you click "li.parent_folder" again. I can get it to do this but I have a problem. When I click on the "li.parent_folder" all the "ul.submenu" disapear instead of just the one that is the child of it.

What would be the correct jquery code to accomplish this? (Oh, I'm using jquery ui also in this project

What I have right now is this:

$('li.parent_folder').click(function() { $('li.parent_folder > ul.submenu').hide(); });


Try this

$('li.parent_folder').click(function() {

  // +this+ var refers to the +li+ that was clicked.

  // .children() gets the children of each element in the set of matched elements, optionally filtered by a selector.
  $(this).children('ul.submenu').hide();
});

Here's more information on jQuery .children() method


Edit:

updated method from .find() to .children() based on @Gumbo's recommendation


$ does not maintain any kind of magical context - you'll have to tell it if you want to start looking from a certain element. In an even handler, this points to the element the handler is attached to. Try

$(this).find(">ul.submenu").hide();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号