使用jQuery自动编号标题H1-H6

cuk*_*eka 8 html jquery automation html-heading

我阅读了相关的帖子,但没有找到IE的解决方案,所以我要求一个jQuery解决方案来解决这个问题:

我有一些像这样嵌套的层次标题

<h1> heading 1</h1> 
<h2> subheading 1</h2>
<h1> heading 2</h1> 
<h2> subheading 1</h2>
<h2> subheading 2</h2>
Run Code Online (Sandbox Code Playgroud)

我需要一些像这样的自动标题输出:

1. heading 1
1.2 subheading 1
2. heading 2
2.1. subheading 1
2.2. subheading 2
Run Code Online (Sandbox Code Playgroud)

有没有办法在IE6 +中使用jQuery或类似方法实现这一点?

Dav*_*und 5

这是我的看法:

var segments = [];

$(':header').each(function() { 

  var level = parseInt(this.nodeName.substring(1), 10);

  if(segments.length == level) {
    // from Hn to another Hn, just increment the last segment
    segments[level-1]++;
  } else if(segments.length > level) {
    // from Hn to Hn-x, slice off the last x segments, and increment the last of the remaining
    segments = segments.slice(0, level);
    segments[level-1]++;
  } else if(segments.length < level) {
    // from Hn to Hn+x, (should always be Hn+1, but I'm doing some error checks anyway)
    // add '1' x times.
    for(var i = 0; i < (level-segments.length); i++) {
      segments.push(1);
    }
  }

  $(this).text(segments.join('.') + '. ' + $(this).text());

});
Run Code Online (Sandbox Code Playgroud)

所有级别的工作示例,H1 - H6


Jer*_*NER 5

另一种可能性

var indices = [];

function addIndex() {
  // jQuery will give all the HNs in document order
  jQuery('h1,h2,h3,h4,h5,h6').each(function(i,e) {
      var hIndex = parseInt(this.nodeName.substring(1)) - 1;

      // just found a levelUp event
      if (indices.length - 1 > hIndex) {
        indices= indices.slice(0, hIndex + 1 );
      }

      // just found a levelDown event
      if (indices[hIndex] == undefined) {
         indices[hIndex] = 0;
      }

      // count + 1 at current level
      indices[hIndex]++;

      // display the full position in the hierarchy
      jQuery(this).prepend(indices.join(".")+" "+this.tagName);

  });
}

jQuery(document).ready(function() {
  addIndex();
});
Run Code Online (Sandbox Code Playgroud)