質問

この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 sをアコーディオンヘッダーとして使用し、各 div.section の残りのコンテンツを各アコーディオンパネルのコンテンツとして使用します。 (注:見出しは、ネストに応じてh2からh6までのいずれかになります)。

DOMツリーが再構築され、 h3 が各 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