Javascript toggle with Bootstrap collapse plugin

2019-02-16 18:53发布

问题:

I try to use the toggle function of the Bootstrap collapse plugin programmatically. I manage to toggle a div when I click on the link in accordion-heading but it works only once, that is to say I cannot click again to hide the div.

Here is my code :

<div id="accordion" class="accordion">
    <div class="accordion-group">
        <div class="accordion-heading">
            <a id="program${bean.id}" data-parent="#accordion" 
                   class="accordion-toggle">
            ...
            </a>
        </div>
        <div id="collapse${bean.id}" class="accordion-body collapse">
            <div class="accordion-inner">
            ...
        </div>
    </div>
</div>

And later in the JSP :

$.each($('#accordion a.accordion-toggle'), function(i, link){
    $(link).on('click', 
        function(){
            // ...
            $('#collapse' + id_of_a_bean).collapse({
                toggle : true,
                parent : '#accordion'
            });
            // ...
        }
    )
});

Did I miss something?

回答1:

I would guess this happened to a lot of people.

When you call the collapse function (FYI or any bootstrap function), if you pass an object it means that you initiate the collapse. The toggle option only toggles once on invocation (doc).

You have to call once with the parameters, and then call only with the action, as a string.

$.each($('#accordion a.accordion-toggle'), function(i, link){
    var $collapsible = $('#collapse' + id_of_a_bean); // Let's be thorough

    $collapsible.collapse({
        toggle : true, // May not be necessary anymore
        parent : '#accordion'
    });

    $(link).on('click', 
        function(){
            // ...
            $collapsible.collapse('toggle'); // Here is the magic trick
            // ...
        }
    );
});

Live demo : http://jsfiddle.net/Sherbrow/uycBa/

Just to be precise, you can only call once the init process, since it aborts if you have already done it on the same element. That's why it worked only one time.



回答2:

Similar problem, I just check if the element is visible:

$("#myDiv").is(":visible") ? $("#myDiv").collapse('hide') : /*do nothing*/;


回答3:

I found that simply invoking the collapse twice, once with parent and once without, does the trick quite nicely - this solution was preferable in my solution due to the hierarchy.

onclick="
$('@("#collapse" + lead.LeadId)').collapse({parent: '#accordion', toggle: true});
$('@("#collapse" + lead.LeadId)').collapse('toggle');"