jQuery下拉菜单从功能中排除子项

时间:2011-08-02 08:35:25

标签: javascript jquery

我有类似的东西

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

我希望#downdown-menu菜单可点击但不是它的孩子所以我这样做了:

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

这适用于后台但不适用于表单节点... 我认为问题是由foldoutstuff上的toggle()引起的

请告知

2 个答案:

答案 0 :(得分:0)

你是否试图阻止儿童的事件传播?

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

答案 1 :(得分:0)

@ Svetlin答案的另一种方法(需要更少的处理程序),如下:

$(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();
        }
    });
});

请参阅Event对象的target属性

相关问题