【问题标题】:jQuery click is not bubbling up to parentjQuery点击没有冒泡到父级
【发布时间】:2014-04-24 04:48:21
【问题描述】:

当点击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');
    };  
});

【问题讨论】:

  • 要将事件冒泡到 li,您需要将 click 绑定到 li 而不是 div.arrow

标签: jquery click event-bubbling


【解决方案1】:

在这里查看演示,http://jsfiddle.net/LFp5n/

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

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
  • $(this).parent().children('span.sibling') 是我为使给定问题工作而添加的唯一部分,其余部分已经完成。感谢您的建议。
【解决方案2】:

我认为您可以将代码缩短为:

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

Fiddle Demo

【讨论】:

  • 我很欣赏代码缩短。我无法让 toggleClass 工作。但是,箭头(或跨度)仍然没有触发点击事件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 2021-09-05
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 2015-09-30
相关资源
最近更新 更多