jQuery自动标题编号
我在网站上有10-15个H2标签字幕的文章。 有点喜欢。
Name of article
Subtitle
.....
Subtitle
.....
Subtitle
.....
Subtitle
.....
那么,问题是如何通过jQuery按降序自动为每个H2标签(副标题)提供数字?
Name of article
15.Subtitle
.....
14.Subtitle
.....
13.Subtitle
.....
12.Subtitle
.....
我知道如何通过CSS计数器来做,但文章可以包含不同数量的字幕。 我已经使用jQuery主题检查了类似的标题自动编号H1-H6 ,但它不是我想要的。
这应该有所帮助
var h2Elements = $('.content').find('h2'); var h2ElemCount = h2Elements.length; $(h2Elements).each(function(i) { $(this).prepend(h2ElemCount - i + '. '); });
Name of article
Subtitle
.....
Subtitle
.....
Subtitle
.....
Subtitle
.....
您可以使用each
函数向后计算。
allItems = $("h2").length; $("h2").each(function (index){ $(this).prepend(allItems - index + ". "); });
Name of article
Subtitle
.....
Subtitle
.....
Subtitle
.....
Subtitle
.....
试试这个:
var h2Length = $("h2").length; $("h2").each(function(i,obj) { $(obj).html(h2Length +". "+$(obj).html()); h2Length--; });