jQuery 标题自动编号

jQuery automatic heading numbering

我网站上的文章有 10-15 个 H2 标签字幕。有点像。

<h1>Name of article</h1>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>

那么,问题是如何通过jQuery自动给每个H2标签(副标题)降序编号?

<h1>Name of article</h1>
<h2>15.Subtitle</h2>
<p>.....</p>
<h2>14.Subtitle</h2>
<p>.....</p>
<h2>13.Subtitle</h2>
<p>.....</p>
<h2>12.Subtitle</h2>
<p>.....</p>

我知道如何通过 CSS 计数器做到这一点,但文章可以包含不同数量的字幕。我检查了类似的 Automatic Numbering of Headings H1-H6 using jQuery 主题,但这不是我想要的。

试试这个:

var h2Length = $("h2").length;
$("h2").each(function(i,obj) { 
  $(obj).html(h2Length +". "+$(obj).html());
  h2Length--; 
});

您可以使用 each 函数倒数。

allItems = $("h2").length;
$("h2").each(function (index){
  $(this).prepend(allItems - index + ". ");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Name of article</h1>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>
<h2>Subtitle</h2>
<p>.....</p>

这应该有帮助

var h2Elements = $('.content').find('h2');
var h2ElemCount = h2Elements.length;
$(h2Elements).each(function(i) {
  $(this).prepend(h2ElemCount - i + '. ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="content">
  <h1>Name of article</h1>
  <h2>Subtitle</h2>
  <p>.....</p>
  <h2>Subtitle</h2>
  <p>.....</p>
  <h2>Subtitle</h2>
  <p>.....</p>
  <h2>Subtitle</h2>
  <p>.....</p>
</div>