下面的代码从HTML头生成带有可折叠子节的目录。我是为一个WordPress网站做的,所以我可以使用PHP或JQuery/JavaScript。我使用PHP生成ToC和JQuery的HTML以折叠/取消折叠部分。
代码运行良好,但我想知道它是否可以更简单/更健壮。
PHP在这里:https://paiza.io/projects/fyq6rNEs5H6AO77DkDRRXQ。它输出JSFiddle:https://jsfiddle.net/yu51a5/jasngvfz/37/中的HTML代码。
PHP代码:
$content=" {yu_TOC}A1a1A2a2 B1b1B2b2 C1c1C2c2 D1d1 E1e1 F1f1";
$start_text = strpos($content, '}') + 1;
$toc_title = 'Table Of Contents';
$id_title = /*sanitize_title*/($toc_title);
$index = 1;
$tableOfContents = "";
$old_level = 0;
$maybe_button = "";
// Insert the IDs and create the TOC.
$content = preg_replace_callback('#<(h[1-9])(.*?)>(.*?)#si', function ($matches) use (&$index, &$tableOfContents, &$old_level, &$id_title, &$toc_title, &$maybe_button) {
$tag = $matches[1];
$toc_entry_title = strip_tags($matches[3]);
$hasId = preg_match('#id=("|”)(.*?)\1[\s>]#si', $matches[2], $matchedIds);
$id = $hasId ? $matchedIds[2] : ($id_title . '-' . $index++ . '-' . /*sanitize_title*/($toc_entry_title));
$new_level = intval($tag[1]);
// is not closed, because we might want to add a button
$tableOfContents_entry = "$toc_entry_title";
if ($new_level > $old_level) { // $new_level = $old_level + 1
// adding a button + other html from the previous iteration
$tableOfContents .= $maybe_button . $tableOfContents_entry;
} else {
// close the 's
for ($x = $new_level; $x < $old_level; $x++) {
$tableOfContents_entry = "" . $tableOfContents_entry;
}
$tableOfContents .= "" . $tableOfContents_entry;
}
// creating html in case it is needed at the next iteration
$maybe_button = '';
$old_level = $new_level;
return "<$tag $matches[2] id='$id'>$matches[3]↑ Back To $toc_title ↑";
}, $content);
// make sure all divs are closed
$nb_opening_divs = preg_match_all('//i', $tableOfContents, $matches);
$nb_closing_divs = preg_match_all('/<\/div>/i', $tableOfContents, $matches);
for ($x = $nb_closing_divs; $x < $nb_opening_divs; $x++) {
$tableOfContents .= "";
}
$result = "$toc_title" . '' . $tableOfContents . '' . trim(substr($content, $start_text));
echo $result;JQuery代码:
$('.toc_button').click(function() {
if ($(this).val() === "-") {
$(this).val("+");
} else {
$(this).val("-");
}
$('#div_' + this.id).toggle();
});发布于 2019-12-21 07:03:06
我发现您的php脚本非常难读。维护这个脚本肯定需要大量的时间投资。
您正在对输入进行太多的preg_手术,可以准备成为有效的html。通过适当的DOM解析工具处理html要可靠得多。我喜欢的工具是DOMDocument,当它使节点定位更清晰/更简单时,我经常将它与XPath配对。
我没有时间完全重写您的脚本,但这正是我推荐的。
您不应该需要在最后抛出更多的
来“清除”生成的html。
https://codereview.stackexchange.com/questions/234414
复制相似问题