javascript – 使用jQuery将头部( – 标签)解析为有序列表?

前端之家收集整理的这篇文章主要介绍了javascript – 使用jQuery将头部( – 标签)解析为有序列表?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在根据标题结构制作一个有序列表样式的目录,这样:
<h1>lorem</h1>
<h2>ipsum</h2>
<h2>dolor</h2>
<h3>sit</h3> 
<h2>amet</h2>

变为:

> lorem

> ipsum
> dolor

>坐下

> amet

这就是我目前正在做的事情:

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

哪个有效,但似乎缺乏优雅.是否有更智能/更快/更强大的方法来做到这一点?

解决方法

jQuery实现:
var $el,$list,$parent,last_depth;
$list = $('ol.result');
$parent = [];
$parent[1] = $list;
last_depth = 1;
$el = 0;
$('h1,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;
});

也许有人会派上用场))

猜你在找的jQuery相关文章