Prevent child element from collapsing with twitter

2019-09-16 19:25发布

问题:

I have the following list:

  • Root
    • Child1
    • Child2

The root should be collapsible but not the children. With the following code both will collapse if I click on one of them. How can I accomplish to prevent children from being collapsed?

<li data-toggle="collapse" data-target="#root"><a href="#">Root</a>
    <ul class="nav nav-list collapse" id="root">
        <li><a href="some_url">Child1</a></li>
        <li><a href="some_url">Child2</a></li>
    </ul>
</li>

Edit: Better approach to describe what I want.

  1. Root is collapsed from start. If I click on root it should show the children (works with code above) and if I click root again it should hide the children (works too)
  2. Once children are displayed I click on a child. This click will trigger collapse and hides the children again. (this is what I'm trying to prevent)

jsfiddle: http://jsfiddle.net/MgcDU/4537/

回答1:

Move the data-toggle and data-target attributes to the a element, like

<li><a href="#" data-toggle="collapse" data-target="#root">Root</a>
    <ul class="nav nav-list collapse" id="root">
        <li><a href="#">Child1</a></li>
        <li><a href="#">Child2</a></li>
    </ul>
</li>

Having them in the topmost li element makes that element and all its children catch the click events and trigger the collapse. Putting the attributes to a child element limits the scope of the click events handling to just that element (and its children.)



回答2:

I believe what you're trying to do is prevent #root from minimizing when one of its children li is clicked? If so, what you're looking for is event.stopPropogation.

Try adding the following code to your JSFiddle:

$('ul > li').on('click', function(e) { e.stopPropagation(); });

This targets the child li elements, and prevents their click events from bubbling up to the parent li with collapse attributes.



回答3:

$("#root a").click(function (e) {
    return false;
});


回答4:

Since the li tags are descendants of the ul#root there is no way to collapse root without collapsing the child li elements. When root is collapsed the child li tags will not be visible.