开发者

jQuery dropdown menu exclude children from function

开发者 https://www.devze.com 2023-03-24 06:42 出处:网络
I have something like this <div id=\"dropdown-menu\"> <div class=\"visiblestuff\"></div>

I have something like this

<div id="dropdown-menu">
    <div class="visiblestuff"></div>
    <div class="foldoutstuff">
        <form>
            <some input value/>
        </form>
    </div>
</div>

I want the #dropdown-menu to be clickable but not it's children so I did this:

$(function() {
    var DropdownChildren = $('div#dropdown').children();
    $('div#dropdown').not(DropdownChildren).click(function(event) {
        var $this = $(this);
        $this.toggleClass('active');
        $('.foldoutstuff').toggle();
    });
});

This works for the background but not the form nodes... I think the problem is caused by the toggle(开发者_JAVA百科) on foldoutstuff

please advise


Have you tried to stop the event propagation from the children?

$(function() {
    $('div#dropdown').children().click(function(event) {
        event.stopPropagation();
    });
    $('div#dropdown').click(function(event) {
        var $this = $(this);
        $this.toggleClass('active');
        $('.foldoutstuff').toggle();
    });
});


An alternate approach to @Svetlin's answer (which requires less handlers to be bound), is as follows:

$(document).ready(function () {
    $('#dropdown').bind('click', function (e) {
        if (e.target == this) { // Check it was this element clicked on; not a child
            var $this = $(this);
            $this.toggleClass('active');
            $('.foldoutstuff').toggle();
        }
    });
});

See the target attribute of the Event object

0

精彩评论

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