6

次のようなヘッダー構造に基づいて、順序付きリストのスタイルで目次を作成しています。

<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()

これは機能しますが、優雅さが欠けているようです。これを行うためのよりスマート/高速/より堅牢な方法はありますか?

4

2 に答える 2

1

これが私がそれを行う方法です:

http://jsfiddle.net/edi9999/cNHPW/

DOM を上下にトラバースする代わりに、h1..h6 タグごとに親を保存し、現在の li 要素をどこに追加する必要があるかを把握します。$elそしてlast_depthグローバル変数です(そのため$el=0、関数の外に行を置きます)

$list=$('ol.result')
$parent=[]
$parent[1]=$list
last_depth=1
$el=0

$('h1, h2, h3, h4, h5, h6').each ()->
    # get depth from tag name
    depth = +@nodeName[1]
    if depth>last_depth
        $parent[depth]=$('<ol>').appendTo($el)
    $el = $("<li>").text($(this).text())
    $parent[depth].append $el
    last_depth=depth
于 2013-07-14T15:29:29.803 に答える