Jquery选择孩子而不是父母

时间:2013-07-08 14:28:20

标签: jquery parent-child

http://jsfiddle.net/xfPxp/

基本上尝试创建一个多层滑下点击菜单, 我已经将子菜单设置为slideDown,但我无法弄清楚如何停止 当我点击孩子时,来自幻灯片的父母。谢谢你的帮助!

Html Code --------------------------------------------- ---------------------------

<!--Nav Menu 1-->

<ul class="make">Club Car
    <ul class="model" style="display: none">Precedent
        <ul class="product" style="display: none">Brush Guard</ul>
        <ul class="product" style="display: none">Lift Kits</ul>
    </ul>

    <ul class="model" style="display: none">DS
        <ul class="product" style="display: none">Brush Guard</ul>
        <ul class="product" style="display: none">Lift Kits</ul>
    </ul>
</ul>

<!--- Nav Menu 2-->

<ul class="make">E-Z-Go
    <ul class="model" style="display: none">TXT
        <ul class="product" style="display:none">Brush Guard</ul>
        <ul class="product" style="display:none">Lift Kits</ul>
    </ul>

    <ul class="model" style="display: none">RXV
        <ul class="product" style="display:none">Brush Guard</ul>
        <ul class="product" style="display:none">Lift Kits</ul>
    </ul>

Jquery Script --------------------------------------------- -----

<script>
$("ul.make").click(function () {
        if ($(this).children('ul').is(":hidden")) {
            $(this).children('ul').slideDown("fast");
        }
        else {
            $(this).children('ul').slideUp("fast");
        }
});
$("ul.model").click(function () {
    if ($(this).children('ul').is(":hidden")) {
        $(this).children('ul').slideDown("fast");
    }
    else {
        $(this).children('ul').slideUp("fast");
    }
});
</script>

2 个答案:

答案 0 :(得分:3)

使用.stopPropagation event传递给您的函数:

$("ul.make").click(function (event) {
    event.stopPropagation();
    if ($(this).children('ul').is(":hidden")) {
        $(this).children('ul').slideDown("fast");
    } else {
        $(this).children('ul').slideUp("fast");
    }
});

$("ul.model").click(function (event) {
    event.stopPropagation();
    if ($(this).children('ul').is(":hidden")) {
        $(this).children('ul').slideDown("fast");
    } else {
        $(this).children('ul').slideUp("fast");
    }
});

演示:http://jsfiddle.net/xfPxp/1/

答案 1 :(得分:0)

您只需将event.stopPropagation添加到您的函数中。

http://jsfiddle.net/9hQz8/

您的点击事件正在冒泡到另一个功能。

$("ul.make").click(function (event) {
    alert("make " + this.tagName + " " + this.className);
            if ($(this).children('ul').is(":hidden")) {
                $(this).children('ul').slideDown("fast");
            }
            else {
                $(this).children('ul').slideUp("fast");
            }
    event.stopPropagation();
});
$("ul.model").click(function (event) {
    alert("make " + this.tagName + " " + this.className);
        if ($(this).children('ul').is(":hidden")) {
            $(this).children('ul').slideDown("fast");
        }
        else {
            $(this).children('ul').slideUp("fast");
        }
    event.stopPropagation();
});