Javascript 使用count+进行预处理+;
我想把标题改成这样:Javascript 使用count+进行预处理+;,javascript,jquery,Javascript,Jquery,我想把标题改成这样: Greetings Introductions Numbers (etc.) 为此: 1. Greetings 2. Introductions 3. Numbers (etc.) 所以我写了这个: var outlineCount = 0 $('.page-template-page-outline .entry-content > h2').prepend('<span class="lesson-number">' + out
Greetings
Introductions
Numbers
(etc.)
为此:
1. Greetings
2. Introductions
3. Numbers
(etc.)
所以我写了这个:
var outlineCount = 0
$('.page-template-page-outline .entry-content > h2').prepend('<span class="lesson-number">' + outlineCount++ + '.</span> ')
我做错了什么?您没有在每个元素上循环,然后在内容前面加上前缀。而是将其应用于jQuery集合中的所有元素 因此,它将是
0
,因为outlineCount
的值仅在+
后缀运算符之后是1
$('.page-template-page-outline .entry-content > h2').each(function(i) {
$(this).prepend('<span class="lesson-number">' + (i + 1) + '.</span>')
});
$('.页面模板页面大纲.条目内容>h2')。每个(函数(i){
$(this).prepend(“”+(i+1)+.”)
});
在上面的代码中,我们使用在回调中传递的索引,并向其中添加一个索引。不需要单独的计数器。您正在将一个“const”字符串作为'+0+'的前缀
u必须知道,prepend在代码中只被调用一次
这可能是解决办法
var outlineCount = 0
$('.page-template-page-outline .entry-content > h2').each(function(){
$(this).prepend('<span class="lesson-number">' + outlineCount++ + '.</span> ');
})
var outlineCount=0
$('.页面模板页面大纲.条目内容>h2')。每个(函数(){
$(this.prepend(“”+outlineCount++');
})
传递给prepend方法的参数在调用该方法之前解析一次;i、 e
“+outlineCount++.”
决定:
'0'
然后将其前置到与CSS选择器'匹配的每个元素。页面模板页面大纲。条目内容>h2'
您需要迭代返回的每个元素,以使方法正常工作,例如
$('.page模板page outline.entry content>h2')。每个(函数(索引,元素){
元素。前置(“”+++outlineCount+”);
});
这可能是离题了,因为它没有回答您遇到的问题(以及前面的回答),但您可以使用
元素获得自动编号的列表,并借助和jquery函数将其插入现有页面
但是,如果有可能,最好的解决方案应该是直接更改html:
<div class="entry-content">
<ol>
<li><h2>Greetings</h2></li>
<li><h2>Introductions</h2></li>
<li><h2>Numbers</h2></li>
</ol>
</div>
问候
介绍
数字
$('.page模板page outline.entry content').wrapInner('');
$('.page模板页大纲.条目内容>ol>h2')。换行('')代码>
问候语
介绍
数字
对字符串求值,outlineCount等于0;然后,该字符串在每个元素前面加上前缀。
<div class="entry-content">
<ol>
<li><h2>Greetings</h2></li>
<li><h2>Introductions</h2></li>
<li><h2>Numbers</h2></li>
</ol>
</div>