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

发布于 2024-10-19 11:36:51 字数 539 浏览 2 评论 0原文

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

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

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

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

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

踏月而来 2024-10-26 11:36:51

这是我的看法:

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

});

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

Here's my take on it:

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

});

Working example on all levels, H1 - H6

青朷 2024-10-26 11:36:51

另一种可能性

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

another possibility

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();
});
冬天的雪花 2024-10-26 11:36:51

老实说,简单来说,一旦我们可以获得每个

标签之后和下一个标签之前的所有

标签,问题就解决了

标签,对吧?

这段代码已经成功并且工作得很好

$("h1").each(function(mainHeadIndex)
 {
     // Numbering the main heads
     $(this).html(mainHeadIndex +1 +'. ' + $(this).html());

     // Find all the h2 tags right under this particular main head
     $(this).nextUntil("h1").filter("h2").each(function(subIndex)
      {
          // calculate the right sub head number
          var newSubIndex = subIndex+1;
          // Numbering the sub heads
          $(this).html(mainHeadIndex +1 +'.'+ newSubIndex +$(this).html());
      });
  })

你可以在这个链接上测试它

PS:谢谢你MatejB ,在你发帖之前我不知道 jsfiddle.com :)

honestor, simply speaking, the problem will be solved once we can get all the <h2> tags that follows right after every <h1> tag and just before the next <h1> tag, right ?

This code has made it and working just fine

$("h1").each(function(mainHeadIndex)
 {
     // Numbering the main heads
     $(this).html(mainHeadIndex +1 +'. ' + $(this).html());

     // Find all the h2 tags right under this particular main head
     $(this).nextUntil("h1").filter("h2").each(function(subIndex)
      {
          // calculate the right sub head number
          var newSubIndex = subIndex+1;
          // Numbering the sub heads
          $(this).html(mainHeadIndex +1 +'.'+ newSubIndex +$(this).html());
      });
  })

you can test it on this link

P.S: thanks for you MatejB, I didn't know jsfiddle.com before your post :)

白芷 2024-10-26 11:36:51

这对我有用:

var i = 0;
var j = 0;
$('h1').each(function(index, element){
    i++;
    $(element).text(i + '. ' + $(element).text());

    j = 1;
    $(element).nextUntil('h1').each(function(subindex, subelement){
        if (!$(this).is('h2')) return; // so subelements other than h2 can be left alone
        j++;
        $(subelement).text(i + '.' + j + '. ' + $(subelement).text());
    });
});

jsfiddle 上的工作示例

This works for me:

var i = 0;
var j = 0;
$('h1').each(function(index, element){
    i++;
    $(element).text(i + '. ' + $(element).text());

    j = 1;
    $(element).nextUntil('h1').each(function(subindex, subelement){
        if (!$(this).is('h2')) return; // so subelements other than h2 can be left alone
        j++;
        $(subelement).text(i + '.' + j + '. ' + $(subelement).text());
    });
});

Woking example on jsfiddle.

不寐倦长更 2024-10-26 11:36:51

我认为你应该将 H2 副标题包装在 DIV 中,然后使用以下代码:

$(document).ready( function() {
    var result = 0;
    $('h1').each(function(index) {
        $(this).text((index + 1) + '. ' + $(this).text());
        var saveIndexNum = index + 1;
        $(this).next().find('h2').each(function(index) {
            $(this).text(saveIndexNum + '.' +(index + 1) + ' ' + $(this).text());
        });
    });
});

试试这个


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
    var result = 0;
    $('h1').each(function(index) {
        $(this).text((index + 1) + '. ' + $(this).text());
        var saveIndexNum = index + 1;
        $(this).next().find('h2').each(function(index) {
            $(this).text(saveIndexNum + '.' +(index + 1) + ' ' + $(this).text());
        });
    });
});
</script>
<style>
h1
{
     color:red;
}
.subheading h2
{
    color:green;
}
.subheading
{
    background:#e2e2e2;
}
</style>
</head>
<body>
<h1> heading 1</h1> 
<div class="subheading">
    <h2> subheading 1.1</h2>
</div>
<h1> heading 2</h1> 
<div class="subheading">
    <h2> subheading 2.1</h2>
    <h2> subheading 2.2</h2>
    <h2> subheading 2.3</h2>
    <h2> subheading 2.4</h2>
    <h2> subheading 2.5</h2>
</div>
<h1> heading 3</h1> 
<div class="subheading">
    <h2> subheading 3.1</h2>
    <h2> subheading 3.2</h2>
</div>
<h1> heading 4</h1> 
<div class="subheading">
    <h2> subheading 4.1</h2>
    <h2> subheading 4.2</h2>
</div>
</body></html>

I think you should wrap H2 subheadings in DIV then use the following code:

$(document).ready( function() {
    var result = 0;
    $('h1').each(function(index) {
        $(this).text((index + 1) + '. ' + $(this).text());
        var saveIndexNum = index + 1;
        $(this).next().find('h2').each(function(index) {
            $(this).text(saveIndexNum + '.' +(index + 1) + ' ' + $(this).text());
        });
    });
});

try this


<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
    var result = 0;
    $('h1').each(function(index) {
        $(this).text((index + 1) + '. ' + $(this).text());
        var saveIndexNum = index + 1;
        $(this).next().find('h2').each(function(index) {
            $(this).text(saveIndexNum + '.' +(index + 1) + ' ' + $(this).text());
        });
    });
});
</script>
<style>
h1
{
     color:red;
}
.subheading h2
{
    color:green;
}
.subheading
{
    background:#e2e2e2;
}
</style>
</head>
<body>
<h1> heading 1</h1> 
<div class="subheading">
    <h2> subheading 1.1</h2>
</div>
<h1> heading 2</h1> 
<div class="subheading">
    <h2> subheading 2.1</h2>
    <h2> subheading 2.2</h2>
    <h2> subheading 2.3</h2>
    <h2> subheading 2.4</h2>
    <h2> subheading 2.5</h2>
</div>
<h1> heading 3</h1> 
<div class="subheading">
    <h2> subheading 3.1</h2>
    <h2> subheading 3.2</h2>
</div>
<h1> heading 4</h1> 
<div class="subheading">
    <h2> subheading 4.1</h2>
    <h2> subheading 4.2</h2>
</div>
</body></html>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文