添加手风琴窗格,手风琴不起作用

时间:2012-09-12 14:13:26

标签: jquery accordion

我可以动态添加新的手风琴窗格,但它们不起作用。有任何想法吗?我假设它们没有被初始化,因为它们是动态添加的。它们出现在我添加它们时,它们只是不会变得动画。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>MLE Editor</title>
    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

    <link href="Styles/site.css" rel="stylesheet" type="text/css" />    

<script type="text/javascript">
    $(document).ready(function()
    {
        //Add Inactive Class To All Accordion Headers
        $('.eventHeader').toggleClass('inactive-header');

        //Set The Accordion Content Width
        var contentwidth = $('.eventHeader').width();
        $('.eventContent').css({ 'width': contentwidth });

        //Open The First Accordion Section When Page Loads
        //$('.eventHeader').first().toggleClass('active-header').toggleClass('inactive-header');
        //$('.eventContent').first().slideDown().toggleClass('open-content');

        // The Accordion Effect
        $('.eventHeader').click(function () {
            if($(this).is('.inactive-header')) {
                $('.active-header').toggleClass('active-header').toggleClass('inactive-header').next().slideToggle().toggleClass('open-content');
                $(this).toggleClass('active-header').toggleClass('inactive-header');
                $(this).next().slideToggle().toggleClass('open-content');
            }

            else {
                $(this).toggleClass('active-header').toggleClass('inactive-header');
                $(this).next().slideToggle().toggleClass('open-content');
            }
        });

        return false;
    });

    function addEvent() {
        var eventsContainer = document.getElementById('eventsContainer');
        var events = eventsContainer.innerHTML;
        events = events + '<h2 class="eventHeader">New event</h2><div class="eventContent"><p>Event options</p></div>';
        eventsContainer.innerHTML = events;
    }
</script>
</head>
<body>
    <form id="form1" runat="server">        
        <div id="eventOptions">
            <a href="javascript:addEvent();">Add Event</a>
            <br />
            <div id="eventsContainer"> 
            <h2 class="eventHeader">Old event</h2><div class="eventContent"><p>Event options</p></div>
            </div>
        </div>
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

让手风琴处理新项目,只需将点击处理程序更改为:

$(document).on('click','.eventHeader',function () {
  if($(this).is('.inactive-header')) {
    $('.active-header').toggleClass('active-header').toggleClass('inactive-header').next().slideToggle().toggleClass('open-content');
    $(this).toggleClass('active-header').toggleClass('inactive-header');
    $(this).next().slideToggle().toggleClass('open-content');
  }

  else {
    $(this).toggleClass('active-header').toggleClass('inactive-header');
    $(this).next().slideToggle().toggleClass('open-content');
  }
});

答案 1 :(得分:1)

我会建议在动态添加项目时销毁然后重新创建手风琴的最佳结果。