Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - Add dynamic closed panels in Bootstrap 3 accordion

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

+------------------+
| 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 2 is opened dynamic panels (cloned from Panel 2) are opened. If Panel 2 is closed, dynamic panels are closed.

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?

This is my jQuery code.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

$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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...