jQuery 在 Bootstrap 3 手风琴中添加动态封闭面板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18825975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:34:22  来源:igfitidea点击:

Add dynamic closed panels in Bootstrap 3 accordion

javascriptjqueryhtmltwitter-bootstrap

提问by Ionic? Biz?u

I use Bootstrap 3accordion and I need to add dynamic panels into it. I have something like this:

我使用Bootstrap 3手风琴,我需要在其中添加动态面板。我有这样的事情:

+------------------+
| Panel 1 (closed) |
+------------------+
| Panel 2 (opened) | <-- This is the template panel
| CONTENT          |
+------------------+
| Dynamic panels   | <-- All dynamic panels must be closed, not opened
+------------------+     after they are added

The issue is that if Panel 2is opened dynamic panels (cloned from Panel 2) are opened. If Panel 2is closed, dynamic panels are closed.

问题是,如果打开面板 2,则打开动态面板(从面板 2克隆)。如果面板 2关闭,则动态面板将关闭。

I want all the dynamic panels to be closed and only when their headers are clicked they will be opened (like in Bootstrap example). How can I fix it?

我希望所有动态面板都被关闭,并且只有当它们的标题被点击时它们才会被打开(就像在 Bootstrap 示例中一样)。我该如何解决?

This is my jQuery code.

这是我的 jQuery 代码。

var $template = $(".template");

var hash = 2;
$(".btn-add-panel").on("click", function () {
    var $newPanel = $template.clone();
    // I thought that .in class makes the panel to be opened
    $newPanel.find(".collapse").removeClass("in");
    $newPanel.find(".accordion-toggle").attr("href",  "#" + (++hash))
             .text("Dynamic panel #" + hash);
    $newPanel.find(".panel-collapse").attr("id", hash);
    $("#accordion").append($newPanel.fadeIn());
});

JSFIDDLE

JSFIDDLE

回答by Anup Singh

I just added addClass("collapse")on this line:

我刚刚addClass("collapse")在这一行添加了:

$newPanel.find(".panel-collapse").attr("id", hash).addClass("collapse").removeClass("in");

$newPanel.find(".panel-collapse").attr("id", hash).addClass("collapse").removeClass("in");

var $template = $(".template");

var hash = 2;
$(".btn-add-panel").on("click", function () {
    var $newPanel = $template.clone();
    $newPanel.find(".collapse").removeClass("in");
    $newPanel.find(".accordion-toggle").attr("href",  "#" + (++hash))
             .text("Dynamic panel #" + hash);
    $newPanel.find(".panel-collapse")
             .attr("id", hash)
             .addClass("collapse")
             .removeClass("in");
    $("#accordion").append($newPanel.fadeIn());
});

Fiddle DEMO

小提琴演示