动态应用引导手风琴功能

Applying bootstrap accordion functionality on the fly

本文关键字:手风琴 功能 应用 动态      更新时间:2023-09-26

我们组织的非技术人员需要能够创建引导手风琴,但没有从头开始创建的技能。我的解决方案是允许他们构建应用了一类"手风琴面板"的div,然后从这些div构建手风琴。

到目前为止,我的代码如下,但它没有应用实际的扩展/折叠机制。我该如何让它发挥作用?

<div class="accordion-panel open" id="accordion-panel_open">
   <h4>Why did you do that?</h4><p>fasdfqw fasdf asdf asdf</p>
</div>
<div class="accordion-panel" desc="title of this panel" id="accordion-panel">
   strong text<h4>No really...Why did you do that?</h4><p><br>dfasd fasdf asdf asdf asdf sadf sdf</p>
</div>
<script>
$(document).ready( function() {
  var $code = false;
  var $panels = $(".accordion-panel");
  if ($panels.length > 0) {
    var $panelloc = $panels.last().after('<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">');
    var i=1;
    $panels.each(function() {
      var $this = $(this);
      var $heading = $this.find("h4");
      var headingtext = $heading.text();
      $heading.remove();
      var panelcode = '<div class="panel panel-default"><div class="panel-heading" role="tab" id="panel'+i+'"><h4 class="panel-title"><a role="button" data-toggle="collapse" data-parent="#accordion" href="#info'+i+'" aria-expanded="true" aria-controls="info'+i+'">'+headingtext+'</a></h4></div><div id="info'+i+'" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="panel'+i+'"><div class="panel-body">'+$this.text()+'</div></div></div>';
      $("#accordion").append(panelcode);
      i++;
      $this.remove();
    });
  }
});
</script>

我会让他们的代码结构有点不同,如下所示:

<div id="accordian">
    <div class="panel open">
       <h4 class="title">Why did you do that?</h4>
       <div class="content">
            <p>fasdfqw fasdf asdf asdf</p>
        </div>
    </div>
    <div class="panel">
        <h4 class="title">title of this panel</h4>
        <div class="content">
       strong text<h4>No really...Why did you do that?</h4>
            <p>dfasd fasdf asdf asdf asdf sadf sdf</p>
        </div>
    </div>
</div>

这对他们想做什么更明确,你不需要他们在那里放任何功能id,除了"accordian"。

这是我要使用的脚本:

$('#accordian')
    .addClass('panel-group');
$('#accordian .panel')
    .addClass('panel-default');
$('#accordian h4.title')
    .removeClass('title')
    .addClass('panel-title')
    .each( function(id){
        $(this).wrapInner('<a data-toggle="collapse" data-parent="#accordion" href="#ac' + id + '"></a>');
    })
    .wrap( '<div class="panel-heading"></div>' );
$('#accordian .content')
    .removeClass('content')
    .addClass('panel-collapse collapse')
    .addClass( function(){
        return $(this).parent().hasClass('open') ? 'in':'';
    })
    .each( function(id){
        $(this).attr('id', 'ac' + id);
    })
    .wrapInner('<div class="panel-body"></div>');

这是一个jsfiddle:https://jsfiddle.net/mckinleymedia/hshqgvk8/