开发者

jQuery | Click child, hides parent

开发者 https://www.devze.com 2022-12-29 20:39 出处:网络
Hey, I have a list of using ul and li: <span class=\"important\">Show/Hide</span> <div id=\"important\" class=\"hidden\">

Hey, I have a list of using ul and li:

<span class="important">Show/Hide</span>

<div id="important" class="hidden">
    <ul class="sub">
     <li>
            Value one
        </li>
        <li class="child">
            <img src="../img/close.png" />
 开发者_运维百科       </li>
    </ul>
</div>

$(".important").click(function () {
  $("#important").slideToggle("fast");
});

When the child (class="child") is clicked on, it should slide up the div (id="important"), however, there are other lists that have different IDs, I want the div to slide up when the child is clicked

I did this:

$(".child").click(function () {
  $(".child < div").slideUp("fast");
});

I have no idea how to make it work, I've done other combinations, can't seem to do it.


You can do it using .closest(), like this

$(".child").click(function() {
  $(this).closest("div").slideUp();
});

This goes from the .child you clicked on up the the neatest <div> ancestor and slides it up. If you may have other divs between the child and parent, then I suggest giving the <div> you do want closed a class, and changing the closest call to look for that specific <div>, like this:

$(".child").click(function() {
  $(this).closest("div.classToClose").slideUp();
});


I would use the parent() selector, this is the best (my opinion) way to make sth like this :)


I think you need the ":parent" selector, in your case it would be:

$(".child:parent").slideUp("fast");

For other selectors, please have a look at: http://api.jquery.com/category/selectors/

0

精彩评论

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

关注公众号