我有一些代码:
$('section').each(function() {
var the_id;
var list_item;
$(this).find('h2').each(function() {
the_id = $(this).attr('id');
$('nav > ol').append('<li><a href="#' + the_id + '">' + $(this).text() + '</a></li>');
$(this).siblings('h3').each(function(i) {
the_id = $(this).attr('id');
if (i == 0) {
$('nav > ol > li:last').append('<ol></ol>');
}
$('nav > ol > li:last > ol').append('<li><a href="#' + the_id + '">' + $(this).text() + '</a></li>');
});
});
});
它会生成一些 HTML,例如:
<li>
<a href="#example-1">Example 1</a>
<ol>
<li>
<a href="#example-1a">Example 1a</a>
</li>
<li>
<a href="#example-1b">Example 1b</a>
</li>
</ol>
</li>
<li>
<a href="#another-example">Another Example</a>
</li>
<li>
<a href="#last-one">Last One</a>
</li>
<li>
<a href="#just-kidding--another">Just kidding, another</a>
<ol>
<li>
<a href="#this-is-a-sub-header">This is a sub header</a>
</li>
</ol>
</li>
我的问题是,我的 JS 只到我写的为止(h2,然后查找 h3,我必须编写另一个回调来执行 h4,然后再编写 h5 和 h6 .如何编写一个递归函数来执行此操作?
最佳答案
另一种构建 HTML 列表的方法怎么样?我真的不擅长编写/理解递归代码。迭代对我来说通常更容易。
function buildToc(container) {
var html = "", lastLevel = -1;
container.find('h1, h2, h3, h4, h5, h6, h7, h8, h9').each(function() {
var $this = $(this);
var level = this.tagName.match(/H(\d)/)[1];
if (lastLevel < level) {
html += "<ol>";
}
if (lastLevel > level) {
html += "</ol>";
}
html += "<li><a href='"+ this.id + "' >" + $this.text() + "</a></li>";
lastLevel = level;
});
return html;
}
$('nav').append( buildToc( $('article section') ) );
我在您的页面上运行了它,它复制了您现有的目录。而且您不需要为每个级别编写自定义代码;又快又脏。
关于javascript - 递归 JS 函数列出 Hx HTML 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5425704/