0

我有这个 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>

基本上使用h3s 作为手风琴标题,并将每个中的其余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
4

2 回答 2

1

啊,我找到了解决方案。

使用$.each()

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

不过,还有比这更好的解决方案吗?也许只是使用香草手风琴选项?

于 2008-10-20T07:29:42.843 回答
0

这个怎么样:

$('.accor .section').each(function() {
    $('h3', this).insertBefore($(this));
});
于 2008-10-20T07:38:33.420 回答