简体   繁体   中英

Opening Bootstrap Accordion Panels using Javascript

I'm making an accordion using Bootstrap that I'd like to dynamically add panels to. I have that part working. see this fiddle

I can add panels on the fly and the accordion functions correctly (when you click one panel, it collapses and also closes any previously opened panel )

I would like to add an additional function that upon adding new panels, the expandLast() function opens the last added panel automatically (which in result should close the previously opened panels). But it not only doesn't do that, it also breaks the accordion functionality; all panels remain open unless they're clicked on again. see the code below:

var count = 1;

$('#myBtn').click(function() {

  var parent = document.getElementById("accordion");
  var wrapper = document.createElement('div');
  wrapper.className = "panel panel-default";


  var title = document.createElement('div');
  title.className = "panel-heading";
  title.setAttribute("id", "cartItemTitle");
  title.setAttribute("data-toggle", "collapse");
  title.setAttribute("data-target", "#collapsible-" + count);
  title.setAttribute("data-parent", "#accordion");
  title.innerHTML = "panel: " + count;

  var body = document.createElement('div');
  body.setAttribute("id", "collapsible-" + count);
  body.className = "panel-collapse collapse";
  //body.className="panel-body";
  body.innerHTML = "Lorem ipsum dolor sit amet, habeo novum possim in duo, solet aperiam postulant at eam. Te dolore ullamcorper vim. Semper officiis ad vix. Maluisset aliquando consectetuer ne pro. Mollis docendi at mei, errem dolorem voluptaria sed ea.";

  wrapper.appendChild(title);
  wrapper.appendChild(body);

  parent.appendChild(wrapper);

  count = count + 1;

  expandLast();
});

function expandLast()
{
  var allItems=document.getElementsByClassName("collapse");
  var lastItem=allItems[allItems.length-1];
  var lastItemSelector="#"+lastItem.getAttribute("id");
  $(lastItemSelector).collapse();
}

any idea what's causing this? -Thanks

I refactored the JavaScript that creates the panels to include the containers and anchor tags to give it the proper panel structure. You can modify as necessary.

The main part that you may want to try is triggering the new panel by using something like the following:

$parent.find('> div:last-of-type a').trigger('click');

Here's a working example:

 var count = 1; $('#myBtn').click(function() { var $parent = $('#accordion'); var $wrapper = $('<div>', { class: 'panel panel-default' }); var $panelHeading = $('<div>', { id: 'heading' + count, class: 'panel-heading', role: 'tab' }); var $titleLink = $('<h4>', { class: 'panel-title' }).append($('<a>', { role: 'button', class: 'collapsed', 'data-toggle': 'collapse', 'data-parent': '#accordion', 'href': '#collapsible-' + count, 'aria-expanded': 'true', 'aria-controls': 'collapsible-' + count }).text('New Panel ' + count)); var $panelBody = $('<div class="panel-body">') .text("Lorem ipsum dolor sit amet, habeo novum possim in duo, solet aperiam postulant at eam. Te dolore ullamcorper vim. Semper officiis ad vix. Maluisset aliquando consectetuer ne pro. Mollis docendi at mei, errem dolorem voluptaria sed ea."); var $panelContainer = $('<div>', { id: 'collapsible-'+count, class: 'panel-collapse collapse', role: 'tabpanel', 'aria-labelledby': 'heading'+count }); $wrapper.append($panelHeading.append($titleLink)); $wrapper.append($panelContainer.append($panelBody)); $parent.append($wrapper); $parent.find('> div:last-of-type a').trigger('click'); count++; }); 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <a id="myBtn" class="btn btn-primary">Add Item</a> <hr> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingTwo"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Collapsible Group Item #2 </a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingThree"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Collapsible Group Item #3 </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree"> <div class="panel-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM