使用jQuery将头文件(<h1> - </h1> <h6>标签)解析为有序列表?</h6>

时间:2013-07-02 07:22:42

标签: javascript jquery coffeescript

我正在根据标题结构以有序列表的样式制作目录,以便:

<h1>lorem</h1>
<h2>ipsum</h2>
<h2>dolor</h2>
<h3>sit</h3> 
<h2>amet</h2>

变为:

  • LOREM
    • ipsum的
    • 阿梅特

这就是我目前的做法:

$('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()
的作品,但似乎缺乏优雅。是否有更智能/更快/更健壮的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

jQuery实现:

var $el, $list, $parent, last_depth;
$list = $('ol.result');
$parent = [];
$parent[1] = $list;
last_depth = 1;
$el = 0;
$('h1, h2, h3, h4, h5, h6').each(function () {
    var depth;
    depth = +this.nodeName[1];
    if (depth > last_depth) {
        $parent[depth] = $('<ol>').appendTo($el);
    }
    $el = $("<li>").text($(this).text());
    $parent[depth].append($el);
    return last_depth = depth;
});

也许有人会派上用场))

答案 1 :(得分:1)

以下是我的方式:

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

不是上下遍历DOM,而是存储每个h1..h6标记的父项,而不是知道我必须附加当前li元素的位置。 $ellast_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