문제

나는이 HTML 구조를 가지고 있으며 그것을 아코디언으로 변환하고 싶습니다.

<div class="accor">
    <div class="section">
        <h3>Sub section</h3>
        <p>Sub section text</p>
    </div>
    <div class="section">
        <h3>Sub section</h3>
        <p>Sub section text</p>
    </div>
    <div class="section">
        <h3>Sub section</h3>
        <p>Sub section text</p>
    </div>
</div>

기본적으로 사용 h3아코디언 헤더 및 각각의 나머지 콘텐츠로 div.section 각 아코디언 패널의 내용으로. (또한 참고 : 제목은 둥지에 따라 H2와 H6 사이에있을 수 있습니다).

나는 Dom 트리가 재구성되면 이것이 가장 쉬운 일이라고 생각했다. h3S는 각각 외부에 있었다 div 그것이 기본적으로 아코디언이 작동하는 방식입니다.

    <h3>Sub section</h3>
    <div class="section">
        <p>Sub section text</p>
    </div>

유일한 문제는 제목을 움직이는 방법입니다. (HTML 변경에 액세스 할 수 없습니다).

var $sections = $("div.accor > .section"),
    $headings = $sections.find("> :header")
;
// I figured that inserting each heading to be before its parent might
// be the answer:
$headings.insertBefore($headings.find(":parent"));

// ... but that doesn't do anything
도움이 되었습니까?

해결책

아, 나는 해결책을 찾았다.

사용 $.each()

$headings.each(function(i, el) {
    var $this = $(el), $p = $this.parent();
    $this.insertBefore($p);
});

그래도 이것보다 더 나은 솔루션이 있습니까? 아마도 바닐라 아코디언 옵션을 사용하는 것일까 요?

다른 팁

이건 어때:

$('.accor .section').each(function() {
    $('h3', this).insertBefore($(this));
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top