【问题标题】:jquery-ui accordion - How to dynamically create a new sectionjquery-ui 手风琴 - 如何动态创建新部分
【发布时间】:2018-01-03 10:11:52
【问题描述】:

我想知道是否存在可以使用jQuery UI 添加新部分的方法

这是我到目前为止所做的没有任何错误,但是手风琴不起作用,因为我添加了一个新的

$( function() {
    $( "#accordion" ).accordion();

    $('#addNewSection').on('click', function() {
        var newH3 = document.createElement('h3');
        var newDiv = document.createElement('div');
        var acc = document.getElementById('accordion');
        var number = document.getElementsByTagName('h3').length;

        newH3.innerText = 'Section' + (parseInt(number) + 1) + "(This won't collapse)";
        newDiv.innerText = 'This is a new section after clicking the button';
        acc.appendChild(newH3);
        acc.appendChild(newDiv);
    });
} );
h3 { background-color: "blue"; }
div { background-color: "lightgreen"; }
<div id="accordion">
    <h3>Section 1 (collapsible)</h3>
    <div>
        <p>
        This is the context in section 1
        </p>
    </div>

    <h3>Section 2 (collapsible)</h3>
    <div>
        <p>
        This is the context in section 2
        </p>
    </div>
</div>
<button id="addNewSection">AddOne</button>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

如何解决?或者有什么官方方法可以用吗?

【问题讨论】:

    标签: javascript jquery jquery-ui accordion jquery-ui-accordion


    【解决方案1】:

    您可以在点击事件结束时使用手风琴的refresh 方法(Documentation):

    $( function() {
        $( "#accordion" ).accordion();
    
        $('#addNewSection').on('click', function() {
            var newH3 = document.createElement('h3');
            var newDiv = document.createElement('div');
            var acc = document.getElementById('accordion');
            var number = document.getElementsByTagName('h3').length;
    
            newH3.innerText = 'Section' + (parseInt(number) + 1) + "(This WILL collapse)";
            newDiv.innerText = 'This is a new section after clicking the button';
            acc.appendChild(newH3);
            acc.appendChild(newDiv);
           $( "#accordion" ).accordion("refresh");
        });
    } );
    h3 { background-color: "blue"; }
    div { background-color: "lightgreen"; }
    <div id="accordion">
        <h3>Section 1 (collapsible)</h3>
        <div>
            <p>
            This is the context in section 1
            </p>
        </div>
    
        <h3>Section 2 (collapsible)</h3>
        <div>
            <p>
            This is the context in section 2
            </p>
        </div>
    </div>
    <button id="addNewSection">AddOne</button>
    
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2016-10-22
      • 2014-02-20
      相关资源
      最近更新 更多