具有动态ajax内容的Bootstrap Accordion

时间:2017-07-28 15:35:19

标签: jquery ajax twitter-bootstrap accordion

我想创建一个包含ajax内容的手风琴。

所以,我的HTML是:

<div class="latestinfo panel-group" id="accordion" role="tablist" aria-multiselectable="true">
// DYNAMIC CONTENT HERE
</div>

我的成功ajax是:

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>');
            });
       }

目前,

  • 显示内容
  • 当我点击第一个时,它会打开
  • 当我点击其他时,第一个切换(打开/关闭)

问题是手风琴没有正常工作,如上所述。

1 个答案:

答案 0 :(得分:5)

id 必须是独一无二的(说得很响,想象回声)......

您可以使用index提供的.forEach()来创建唯一的id ;)

您可以使用+在多行上连接字符串...
提高了可读性。

// 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>