简体   繁体   中英

Collapse with dynamic accordions

<div class="panel-group" id="accordion">
      {{#each forms}}
      <div class="panel panel-default">
        <div class="panel-heading">
          <h4 class="panel-title">
            <a data-toggle="collapse" data-parent="#accordion" href=".collapse">
            {{fid}}</a>
          </h4>
        </div>
        <div class="panel-collapse collapse">
          <div class="panel-body">
          {{> form}}
          </div>
        </div>
      </div>
      {{/each}}
    </div>

<template name="form">
  <li class="list-group-item list-group-item-warning">First name : {{fname}}</li>
  <li class="list-group-item list-group-item-warning">Last name : {{lname}}</li>
  <li class="list-group-item list-group-item-warning">Analysis : {{ydata}}</li>

</template>

I am using bootstrap with meteor. I have created a form which adds accordions dynamically according to the form data. The accordions are added successfully. The only problem is it only collapses the first accordion even if I click the second or third one. How can I make the specific accordion collapse when it being added dynamically?

It's a referencing issue you are having. Looking at your code, this line

 <a data-toggle="collapse" data-parent="#accordion" href=".collapse"> 

will be repeated for each of the three accordions dynamically generated.

Meaning your href=".collapse" attribute in the a tag for each accordion will always be pointing to the same <div class="panel-collapse collapse"> element. That explains why only the first accordion (first of its type) opens even when you click the second or third accordion triggers.

To get it all working: Use a dynamically generated ID referencing on your href attribute instead of a class. In other words, use an increment counter or something along those lines. And also make sure you generate a matching ID on your collapse div element. As an example, you could have something like:

<a data-toggle="collapse" data-parent="#accordion" href="{{#dynamicallyGeneratedID}}"> 
  ...

then you could have something like:

<div class="panel-collapse collapse" id="{{dynamicallyGeneratedID}}"> 
  ...

So let's say for accordion one that will result in something like:

 <a data-toggle="collapse" data-parent="#accordion" href="#formOne"> 
   ...

then your panel body will also be:

<div class="panel-collapse collapse" id="formOne">
  ... 

All the best of luck!

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