添加jQuery Accordion元素时,需要新元素默认打开

When adding a jQuery Accordion element, need new element to default open

本文关键字:元素 默认 新元素 Accordion jQuery 添加      更新时间:2023-09-26

我有一个动态创建新元素的手风琴。但是,当我这样做时,我似乎无法让最新的元素默认打开。它总是第一个元素

想法?

HTML:

    <asp:MultiView ID="MainView" runat="server">
        <asp:View ID="View1" runat="server">
            <table style="width: 100%; border-width: 3px; border-color: #C4F691; border-style: solid">
                <tr>
                    <td>
                        <div class="rowClassSpace">
                            &nbsp;</div>
                        <div id="accordion">
                            <a href="#">Make/Model (Insured Vehicle)</a>
                                <div>
                                    <p>
                                        Content
                                    </p>
                                </div>
                        </div>
                        <div>
                            <button id="addAccordion">
                                Add Another Vehicle</button>
                            </div>
                    </td>
                </tr>
            </table>
        </asp:View>
    </asp:MultiView>

JS:

    //  Initialize accordion
    $(document).ready(function () {
        $(function () {
        $("#accordion").accordion();
        });
     });
    //  Adding according sections
    $('#addAccordion').click(function () {
    });
    function addAccordion() {
       var active = $('#accordion').accordion('option', 'active');
       $('#accordion').append('<a href="#">Make/Model (Other Car #)</a><div><p>New data</p></div>').accordion('destroy').accordion({ active: active});
       }

建议使用destroy方法销毁现有的,然后添加新的部分,然后初始化新的手风琴实例。此外,你使用的标记似乎很奇怪,使用<a>标签

通过计算现有部分,您可以将active索引设置为添加新部分之前的部分数量,以便打开添加的最新部分

var template=function(ctr){
   /* using html markup per docs*/
    return '<h3>Section '+ctr+'</h3><div>Content '+ctr+'</div>';
};
var accordOptions={
    collapsible:true,
    active:0
};
var $accord=$('#accordion').accordion(accordOptions);
$('button').click(  addSection);
function addSection(){
    var num_sections=$accord.children('h3').length;
    /* set active index to number of current sections*/
    accordOptions.active=num_sections;
    $accord.accordion('destroy')
            .append( template( num_sections +1 ) )
            .accordion( accordOptions);
}

演示:http://jsfiddle.net/HnVqD/