为什么event.stopPropagation也会停止我的Bootstrap Collapse?

时间:2018-02-07 17:04:27

标签: javascript jquery twitter-bootstrap collapse stoppropagation

我有一个具有#planAdminMenuItem属性的列表项(onclick)。此列表项中包含一个图标(.spinner),该图标将折叠#collapseExample。每当点击.spinner时,我希望它只运行bootstrap collapse。我不希望它运行drawPlanAdmin函数。我已经尝试将event.stopPropagation添加到我的toggleSpinnerLeftMenu函数中,但每当我这样做时,它也会停止引导程序崩溃。父点击被阻止,但是bootstrap崩溃也是如此。

PHP& HTML代码

<ul>            
    <li id="planAdminMenuItem" onclick="plan.drawPlanAdmin();"> 
        Book Plan
        <span class="icn icn-chevron-down spinner" onclick="ui.toggleSpinnerLeftMenu(this,event);" data-toggle="collapse" data-target="#collapseExample" data-aria-expanded="true" aria-controls="collapseExample"></span>
    </li>
    <!-- the collapsable area -->               
    <li id="collapseExample" class="collapse in">
        <ul>
            <li onclick="plan.drawRunListAdmin();">
                Run List View
            </li>
            <li onclick="plan.drawLadderAdmin();"> 
                Ladder View
            </li>               
        </ul>
    </li>
</ul>

THE JS CODE

toggleSpinnerLeftMenu:function(el,event){
    el = jQuery(el);

    if(el.hasClass('icn-chevron-up')){
        el.addClass('icn-chevron-down');
        el.removeClass('icn-chevron-up');
    }else if(el.hasClass('icn-chevron-down')){
        el.addClass('icn-chevron-up');
        el.removeClass('icn-chevron-down');

    }
    event.stopPropagation(); //why is this stopping the collapse also?
},

1 个答案:

答案 0 :(得分:3)

stopPropagation正在完成它的目的。

如果您希望通过单击内部元素来传播父元素,则根本不执行event.stopPropagation

虽然出于某些原因,如果您需要,那么我的建议是:调用函数

toggleSpinnerLeftMenu:function(el,event){
    el = jQuery(el);

    if(el.hasClass('icn-chevron-up')){
        el.addClass('icn-chevron-down');
        el.removeClass('icn-chevron-up');
    }else if(el.hasClass('icn-chevron-down')){
        el.addClass('icn-chevron-up');
        el.removeClass('icn-chevron-down');

    }
    plan.drawPlanAdmin(); // Call the function inside of the child element's click handler.
    event.stopPropagation(); //why is this stopping the collapse also?
},

更新:由于您在评论中更清楚地描述了该问题,该评论的解决方案完全超出了我上面所写的内容,因此我正在使用可能有助于提供帮助的新内容进行更新。

不使用两个事件处理程序,一个使用内联onClick属性而另一个使用Bootstrap的data-collapse,而是使用一个:

$(".spinner").on("click", function(event) { // tip: Give a better id or class name 
    $('#collapseExample').collapse({toggle: true});
    ui.toggleSpinnerLeftMenu(this, event);
}); 

这是执行此操作的一般想法,您可能仍需要对方法调用进行一些调整以适应它。