使用 jQuery 自动编号标题 H1-H6 [英] Automatic Numbering of Headings H1-H6 using jQuery

查看:21
本文介绍了使用 jQuery 自动编号标题 H1-H6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I read related posts, but didn't find a solution for IE, so I ask for a jQuery-solution for this problem:

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

I've some nested hierarchical Headings like this

<h1> heading 1</h1> 
<h2> subheading 1</h2>
<h1> heading 2</h1> 
<h2> subheading 1</h2>
<h2> subheading 2</h2>

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

I need some automated headings output like this:

1. heading 1
1.2 subheading 1
2. heading 2
2.1. subheading 1
2.2. subheading 2

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

Is there a way how this can be achieved using jQuery or alike, working in IE6+?

推荐答案

另一种可能性

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

这篇关于使用 jQuery 自动编号标题 H1-H6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆