我有一个后续问题,Jack 已经回答了我的问题: Wrap segments of HTML with divs (and generate table of contents from HTML-tags) with PHP
我一直在尝试为上面的答案添加一些功能,以获得以下结果。
这是我现在的 HTML:
<h3>Subtitle</h3>
<p>This is a paragraph</p>
<p>This is another paragraph</p>
<h3>Another subtile
<h3>
<p>Yet another paragraph</p>
这就是我想要实现的目标:
<h3 class="current">Subtitle</h3>
<div class="ac_pane" style="display:block;">
<p>This is a paragraph</p>
<p>This is another paragraph</p>
</div>
<h3>Another subtitle</h3>
<div class="ac_pane">
<p>Yet another paragraph</p>
</div>
我一直在尝试修改上面示例中的代码,但无法弄清楚:
foreach ($d->getElementsByTagName('h3') as $h3) {
$ac_pane_nodes = array($h3);
for ($next = $h3->nextSibling; $next && $next->nodeName != 'h3'; $next = $next->nextSibling) {
$ac_pane_nodes[] = $next;
}
$ac_pane = $d->createElement('div');
$ac_pane->setAttribute('class', 'ac_pane');
// Here I'm trying to wrap all tags between h3-sets, but am failing!
$h3->parentNode->appendChild($ac_pane, $h3);
foreach ($ac_pane_nodes as $node) {
$ac_pane->appendChild($node);
}
}
请注意,添加class="current"
到第一个 h3 集和添加style="display:block;"
到第一个集div.ac_pane
是可选的,但非常感谢。