我正在尝试创建一个Bootstrap 4手风琴。我正在使用Ajax调用来获取数据,并且数据正确地记录到控制台。我想做一个ForEach循环,并为JSONP数据集中返回的每个相册在Accordion上附加一张新卡片。
我遇到的问题:首先加载HTML,然后我收到数据,之后没有任何反应,手风琴不会渲染。
如何在所有数据准备好后加载手风琴?
相关HTML(艺术家ID是整数):
<div id="discogAccordion">
<script type="text/javascript">
let url = 'https://api.deezer.com/artist/' + {{ artist_id }} +'/albums?output=jsonp';
</script>
<script type="text/javascript" src="{% static "js/tracklist.js" %}">
</script>
</div>
相关JS(js / tracklist.js):
$(function () {
$.ajax({
url: url,
type: 'GET',
jsonp: 'callback',
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
console.log('all data: ', data);
albumAccordion(data);
},
error: function (x, y, z) {
console.log('x', x);
console.log('y', y);
console.log('z', z);
}
});
});
let albumAccordion = function (data) {
data.data.forEach(function (item, index) {
console.log(item, index);
return $('.discogAccordion').append(
'<div class="card">'+
'<div class="card-header" id="heading'+ index +'">'+
'<h5 class="mb-0">'+
'<button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapse'+ index +'"'+
' aria-expanded="false" aria-controls="collapse'+ index +'">'+
'enim eiusmod high life accusamus terry '+
'</button>'+
'</h5>'+
'</div>'+
'<div id="collapse'+ index +'" class="collapse" aria-labelledby="heading'+ index +'" data-parent="#discogAccordion">'+
'<div class="card-body">'+
'Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf'+
'</div>'+
'</div>'+
'</div>'
);
});
};
答案 0 :(得分:3)
问题是该函数选择了类名.discogAccordion
,但你的手风琴容器有<div id="discogAccordion">
。因此,选择手风琴容器的正确方法是$('#discogAccordion')
...
let albumAccordion = function (data) {
data.data.forEach(function (item, index) {
console.log(item, index);
$('#discogAccordion').append(
'<div class="card">'+
'<div class="card-header" id="heading'+ index +'">'+
'<h5 class="mb-0">'+
'<button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapse'+ index +'"'+
' aria-expanded="false" aria-controls="collapse'+ index +'">'+
item.title+
'</button>'+
'</h5>'+
'</div>'+
'<div id="collapse'+ index +'" class="collapse" aria-labelledby="heading'+ index +'" data-parent="#discogAccordion">'+
'<div class="card-body">'+
'Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf'+
'</div>'+
'</div>'+
'</div>'
);
});
https://www.codeply.com/go/wr9gjn3Xxg
或者,您可以为手风琴提供<div id="discogAccordion" class="discogAccordion">
类名称,然后选择$('.discogAccordion')
的原始函数将起作用。