我有这种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树被重构,这将是最简单的,因此 h3 s在每个 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