使用Bootstrap折叠插件进行Javascript切换 [英] Javascript toggle with Bootstrap collapse plugin

查看:82
本文介绍了使用Bootstrap折叠插件进行Javascript切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以编程方式使用Bootstrap折叠插件的切换功能。
当我在手风琴标题中单击链接时,我设法切换了div,但是它只能工作一次,也就是说,我无法再次单击以隐藏div。

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.

这是我的代码:

<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>

后来在JSP中:

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

我错过了什么吗?

推荐答案

我想很多人都会遇到这种情况。

I would guess this happened to a lot of people.

当您调用崩溃函数(FYI或任何引导函数),如果传递对象,则意味着您启动折叠。 toggle 选项仅在调用时 切换一次(

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
            // ...
        }
    );
});

实时演示: http://jsfiddle.net/Sherbrow/uycBa/

准确地说,您只能调用一次init进程,因为如果您已经在同一元素上完成了此操作。这就是为什么它只能运行一次的原因。

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.

这篇关于使用Bootstrap折叠插件进行Javascript切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆