使用带有奇怪标记的 jQuery 手风琴
我有这个 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
位于每个 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
I have this HTML structure and want to convert it to an accordion.
<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>
Basically using the h3
s as accordion headers, and the rest of the content in each div.section
as the content for each accordion panel. (Also note: the headings could be anything between h2 and h6, depending on their nesting).
I figured that this would be easiest if the DOM tree were restructured so the h3
s were outside each div
since that's how the accordion works by default:
<h3>Sub section</h3>
<div class="section">
<p>Sub section text</p>
</div>
The only problem is: how to move the headings around? (I don't have access to change the 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
啊,我找到了解决方案。
使用
$.each()
有比这更好的解决方案吗? 也许只是使用香草手风琴选项?
Ah, I found the solution.
Using
$.each()
Is there a better solution than this, though? Perhaps just using the vanilla Accordion options?
这个怎么样:
How about this: