【问题标题】:Parse header (<h1> -- <h6> tags) to ordered list, using jQuery?使用jQuery将标题(<h1> - <h6>标签)解析为有序列表?
【发布时间】:2013-07-02 07:22:41
【问题描述】:

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

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

变成:

  • 洛雷姆
    • 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()

哪个有效,但它似乎缺乏优雅。有没有更智能/更快/更稳健的方法来做到这一点?

【问题讨论】:

  • 那是咖啡脚本吗?
  • 确实是这样,但它并不是一个真正的“coffeescript 问题”,而是一个 jquery 问题。
  • 为什么dolor的缩进与sit不同?
  • 您可以使用(':header') 选择器代替h1, h2, h3, ...
  • @JanDvorak:它刚刚被 OP 编辑​​过。

标签: javascript jquery coffeescript


【解决方案1】:

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;
});

也许有人会派上用场))

【讨论】:

    【解决方案2】:

    我会这样做:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2017-04-25
      • 2015-05-27
      • 2015-07-12
      相关资源
      最近更新 更多