jQuery click不会冒泡到父级

时间:2014-04-24 04:48:21

标签: jquery click event-bubbling

单击div.arrow时,其类应切换,折叠的内容应展开/折叠。这是有效的,但div.arrow上的点击事件并没有冒充它的父母li.level1。在相关的说明中,我如何让兄弟姐妹span也被包括在这个冒泡中?

HTML

<ul id="list">
    <li class="level1"><div class="arrow arrow-down"></div>Exact Matches
        <ul id="ul_first" class="level1a">
            <li><b>GE</b> Ab Illo Inventore: ASJK: (2365)</li>
            <li><b>GE</b> Doloremque: PEOJ: (92454)</li>
            <li>Eaque <b>GE</b> Ipsa Quae</li>
            <li>Porro Quisquam <b>GE</b> Est</li>
            <li>Sit Voluptatem <b>GE</b></li>
        </ul>
    </li>   
    <li class="level1"><div class="arrow arrow-right"></div>Advisor <span>(7)</span>
        <ul class="level1a">
            <li>Ab Ill<b>ge</b>o Inventore</li>
            <li>A<b>ge</b>usantium</li>
            <li>Aspernatur Aut<b>ge</b></li>
            <li>Beata<b>ge</b>e Vitae Dicta</li>
            <li>Consequuntur<b>ge</b></li>
            <li>Geloremque</li>
            <li>Geque Ipsa Quae</li>
        </ul>
    </li>   

CSS

li.level1 .arrow-down, li.level1 .arrow-right {
    width: 0; 
    height: 0; 
    position: absolute;
}

li.level1 .arrow-down {
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 7px solid #444;
    left: -16px;
    top: 7px;
}

li.level1 .arrow-right {
    border-top: 5px solid transparent;
    border-bottom: 5px solid transparent;
    border-left: 7px solid #444;
    left: -12px;
    top: 5px;
}

JS

$('div.arrow').click(function(){
    var arrowRight = $(this).hasClass('arrow-right');  
    var arrowDown = $(this).hasClass('arrow-down');
    console.log("R: "+arrowRight);
    console.log("D: "+arrowDown);

    $(this).parent().children('ul.level1a').slideToggle();

    if (arrowRight) {
        $(this).removeClass('arrow-right').addClass('arrow-down');
    } else if (arrowDown) {
        $(this).removeClass('arrow-down').addClass('arrow-right');
    };  
});

2 个答案:

答案 0 :(得分:1)

在此处查看演示,http://jsfiddle.net/LFp5n/

使用$(this).parent().children('span.sibling')选择兄弟姐妹

答案 1 :(得分:0)

我认为你可以缩短你的代码:

$('#list > li').click(function () {
    $(this).find('ul.level1a').slideToggle();
    $(this).find('.arrow').toggleClass('arrow-right arrow-down');
});

<强> Fiddle Demo