简体   繁体   English

解析头( <h1> - <h6> 标签)到有序列表,使用jQuery?

[英]Parse header (<h1> — <h6> tags) to ordered list, using jQuery?

I'm making a table of contents, in the style of an ordered list, based on the header structure, such that: 我正在根据标题结构制作一个有序列表样式的目录,这样:

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

becomes: 变为:

  • lorem LOREM
    • ipsum 存有
    • dolor
      • sit
    • amet 阿梅德

This is how i'm currently doing it: 这就是我目前正在做的事情:

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

which works , but it seems like it lacks elegance. 哪个有效 ,但似乎缺乏优雅。 Is there a smarter / faster / more robust way to do this? 是否有更智能/更快/更强大的方法来做到这一点?

jQuery emplementation: 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;
});

Maybe someone will come in handy)) 也许有人会派上用场))

Here's the way I would do it: 这是我的方式:

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

Instead of traversing the DOM up and down, I store the parent for each h1..h6 tag, and I than know where I have to append the current li element. 我没有上下遍历DOM,而是为每个h1..h6标签存储父节点,而不知道我必须在哪里附加当前的li元素。 $el and last_depth are global variables (That's why I put the line $el=0 outside of the function) $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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM