Вопрос

I'm using jQuery and have managed to paste together a simple accordion which can ONLY have one section of the accordion open at the same time. Each section of the accordion which has subitems has a "+"-sign to indicate this. When the section is clicked and the content is expanded, the "+"-icon switches to a "-". This all works fine and dandy until I need to have 2 (or more) accordions on the same page. The way it works now, the script switches all expanded divs "-"-icons from a "-" to a "+". I only want the +/- icons within the same div as the latest clicked link to switch, the way it is now, all icons of expanded sections are changed when a link is clicked.

Here is the script used:

$(document).ready(function() {

    $(".accordion dd").hide();

    $(".accordion dt a").click(function(){
        $(this).parent().next().siblings("dd:visible").slideUp("slow");
        $(this).parent().next().slideToggle("slow");
        if ($(this).is("expanded")) {
            $(this).toggleClass("expanded");
            } else {
            $(".accordion dt a").removeClass("expanded");
            $(this).addClass("expanded");
        }
        return false;
    });
});

Here is some html. The html below is one instance. If there is more than one list on the page, the html structure below will be duplicated.

<div style="position:relative;" class="regularBorder roundedCorner">
<h2>header</h2>
<dl class="accordion">
    <dt class="roundedCorner navbarBG first noSideBorder">
        <a href="/">Lorem Ipsum 1</a></dt>
    <dd>
        <ul class="accordion noSideBorder">
            <li><a href="#">Lorem ipsum dolor</a></li>
            <li><a href="#">Lorem ipsum dolor</a></li>
        </ul>
    </dd>
    <dt class="roundedCorner navbarBG noSideBorder">
        <a href="/">Lorem Ipsum 2</a></dt>
    <dd>
        <ul class="accordion noSideBorder">
            <li><a href="#">Lorem ipsum dolor</a></li>
            <li><a href="#">Lorem ipsum dolor</a></li>
        </ul>
    </dd>
    <dt class="roundedCorner navbarBG noSideBorder">
        <a href="/">Lorem Ipsum 3</a></dt>
    <dd>
        <ul class="accordion noSideBorder">
            <li><a href="#">Lorem ipsum dolor</a></li>
            <li><a href="#">Lorem ipsum dolor</a></li>
        </ul>
    </dd>
</dl>
</div>

So a simple solution for making this work would be appreciated!

Это было полезно?

Решение

Shouldn't this:

$(".accordion dt a").removeClass("expanded");

Be something like this:

$(this).parents('.accordion').find('dt a').removeClass("expanded");

Другие советы

var selector = '.accordion dt a';
$(selector ).each(function()
{
        $(this).removeClass("expanded");
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top