问题
I want to create an accordion with a content from ajax.
So, my HTML is :
<div class="latestinfo panel-group" id="accordion" role="tablist" aria-multiselectable="true">
// DYNAMIC CONTENT HERE
</div>
and my success ajax is :
success: function(data) {
data.items.forEach(function(e) {
$('.latestinfo').append('<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">' + e.title + '</a></h4></div><div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"><div class="panel-body">' + e.content + '</div></div></div>');
});
}
Currently ,
- The content is displayed
- When i click the first one it open
- When i click other, the first toggle ( open / close )
The problem is that the accordion is not working correctly as I described above.
回答1:
An id
MUST BE UNIQUE (say it loud and imagine echo)...
You can use the index
provided by .forEach()
to create unique id
.
;)
And you can use +
to concatenate a string on multiple lines...
Improves readability.
// Assuming this JSON.
var data = {items:[{title:"ONE",content:"Something-1"},
{title:"TWO",content:"Something-2"},
{title:"THREE",content:"Something-3"}
]
};
var success = function(data) {
data.items.forEach(function(item,index) {
$('.latestinfo').append(
'<div class="panel panel-default">'+
'<div class="panel-heading" role="tab" id="heading_'+index+'">'+
'<h4 class="panel-title">'+
'<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse_'+index+'" aria-expanded="true" aria-controls="collapse_'+index+'">'+
item.title+
'</a>'+
'</h4>'+
'</div>'+
'<div id="collapse_'+index+'" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading_'+index+'">'+
'<div class="panel-body">'+
item.content+
'</div>'+
'</div>'+
'</div>'
);
});
}
// Feaking an ajax response...
success(data);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<div class="latestinfo panel-group" id="accordion" role="tablist" aria-multiselectable="true">
// DYNAMIC CONTENT HERE
</div>
来源:https://stackoverflow.com/questions/45377394/bootstrap-accordion-with-dynamic-ajax-content