[英]Adding class to the UL and LI as per the level
I have the following HTML mark up. 我有以下HTML标记。
<ul class="thumbs">
<li>
<strong>Should be level 0</strong>
</li>
<li>
<strong>Should be level 1</strong>
</li>
<li>
<strong>Should be level 2</strong>
</li>
</ul>
<ul class="thumbs">
<li>
<strong>Should be level 0 -- </strong>
</li>
<li>
<strong>Should be level 1 -- </strong>
</li>
</ul>
and javascript: 和javascript:
var i = 0;
var j = 0;
jQuery('ul.thumbs').each(function(){
var newName = 'ul -level' + i;
jQuery(this).addClass('ul-level-'+i)
.before('<h2>'+newName+'</h2>');
i = i+1;
});
jQuery('ul.thumbs li').each(function(){
jQuery(this).addClass('li-level-'+j)
.append('li-level-'+j);
j = j+1;
});
But the level of the second UL LI is show different. 但是第二UL LI的级别显示不同。
Please help me out in this. 请帮助我。
You need to loop through the <li>
s in each <ul>
separately, by putting the second each
loop (for the <li>
s) inside the first one. 您通过需要循环
<li>
S中的每个<ul>
分开,通过将第二each
循环(对于<li>
或多个)第一个内。
For example: 例如:
var i = 0;
jQuery('ul.thumbs').each(function(){
var newName = 'ul -level' + i;
jQuery(this).addClass('ul-level-'+i)
.before('<h2>'+newName+'</h2>');
i++;
var j = 0;
jQuery(this).children('li').each(function(){
jQuery(this).addClass('li-level-'+j)
.append('li-level-'+j);
j++;
});
});
By the way, each
takes an index parameter, so you don't need your i
and j
variables: 顺便说一下,
each
参数都带有一个索引参数,因此您不需要i
和j
变量:
jQuery('ul.thumbs').each(function(i){
var newName = 'ul -level' + i;
jQuery(this).addClass('ul-level-' + i)
.before('<h2>' + newName + '</h2>')
.children('li').each(function(j) {
jQuery(this).addClass('li-level-' + j)
.append('li-level-' + j);
});
});
(Tested) (测试)
You need to reset j
after each ul
: 您需要在每个
ul
之后重置j
:
var i = 0;
var j = 0;
jQuery('ul.thumbs').each(function(){
var newName = 'ul -level' + i;
jQuery(this).addClass('ul-level-'+i)
.before('<h2>'+newName+'</h2>');
i = i+1;
j = 0;
jQuery('li', this).each(function(){
jQuery(this).addClass('li-level-'+j)
.append('li-level-'+j);
j = j+1;
});
});
(Untested) (未测试)
Also consider this something to do server-side. 还可以考虑在服务器端执行此操作。
For each UL you should be processing the child LI's 对于每个UL,您应该处理子LI的
var i = 0;
var j = 0;
jQuery('ul.thumbs').each(function(){
var newName = 'ul -level' + i;
jQuery(this).addClass('ul-level-'+i)
.before('<h2>'+newName+'</h2>');
i = i+1;
j=0;
jQuery(this).children("li").each(
function(){
jQuery(this).addClass('li-level-'+j)
.append('li-level-'+j);
j = j+1;
}
)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.