Javascript toggle with Bootstrap collapse plugin

点点圈 提交于 2019-12-01 03:27:35

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.

Alex

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

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

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');"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!