次のようなヘッダー構造に基づいて、順序付きリストのスタイルで目次を作成しています。
<h1>lorem</h1>
<h2>ipsum</h2>
<h2>dolor</h2>
<h3>sit</h3>
<h2>amet</h2>
になります:
- ロレム
- イプサム
- 悲しい
- 座る
- アメット
これは私が現在やっている方法です:
$('h1, h2, h3, h4, h5, h6').each ()->
# get depth from tag name
depth = +@nodeName[1]
$el = $("<li>").text($(this).text())
do get_recursive_depth = ()->
if depth is current_depth
$list.append $el
else if depth > current_depth
$list.append( $("<ol>") ) unless $list.children().last().is('ol')
$list = $list.children().last()
current_depth += 1
get_recursive_depth()
else if depth < current_depth
$list = $list.parent()
current_depth -=1
get_recursive_depth()
これは機能しますが、優雅さが欠けているようです。これを行うためのよりスマート/高速/より堅牢な方法はありますか?