简体   繁体   中英

Adding class to the UL and LI as per the level

I have the following HTML mark up.

<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:

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;
  });

JS Bin Link

But the level of the second UL LI is show different.

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.

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:

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 :

  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

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;        
      }
   )

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM