[英]Adding class to the UL and LI as per the level
我有以下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>
和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;
});
但是第二UL LI的級別顯示不同。
請幫助我。
您通過需要循環<li>
S中的每個<ul>
分開,通過將第二each
循環(對於<li>
或多個)第一個內。
例如:
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++;
});
});
順便說一下, 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);
});
});
(測試)
您需要在每個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;
});
});
(未測試)
還可以考慮在服務器端執行此操作。
對於每個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.