jQuery自动标题编号

时间:2017-04-12 14:25:44

标签: jquery automation html-heading css-counter

我在网站上有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主题,但这并不是我想要的。

3 个答案:

答案 0 :(得分:1)

您可以使用each功能向后计算。

&#13;
&#13;
allItems = $("h2").length;
$("h2").each(function (index){
  $(this).prepend(allItems - index + ". ");
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

这应该有帮助

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>

相关问题