Parse header (

tags) to ordered list, u

2019-05-03 04:53发布

问题:

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
    • 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?

回答1:

jQuery emplementation:

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



回答2:

Here's the way I would do it:

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. $el and last_depth are global variables (That's why I put the line $el=0 outside of the function)

$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