jQuery automatic heading numbering

2019-08-07 14:15发布

问题:

I have articles on website with 10-15 H2 tag subtitles. Something likes that.

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

So, question is how to give number for each H2 tag (subtitle) automatically by jQuery in descending order?

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

I know how to do it via CSS counters, but articles can contain different numbers of subtitles. I've checked similar Automatic Numbering of Headings H1-H6 using jQuery topic, but it is not i want exactly.

回答1:

This should help

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>



回答2:

You can numerate backwards by using the each function.

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>



回答3:

Try This:

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