简体   繁体   中英

Increment for each list item

I am trying to increment the z-index of each list item.

This is what I tried so far:

    var photos = $('ul');
  photos.each(function () {

      var photos = $(this).children();
      var photosLen = photos.length;
      if (photosLen > 1) {
          photos.parent().addClass('album');
          var i = 0;
          while (i < photosLen) {

              $(this).children().css({
                  'z-index': i
              });
          }
      }

  });

I expected each list-item would go from z-index: 1; to z-index: 3; But It's not doing that. Just adds the length of the array to each list-item.

HTML: (Code would only apply to the first un-ordered list)

<ul>

    <li><img src="http://i.imgur.com/PuwwFs.jpg" alt=""></li>
    <li><img src="http://i.imgur.com/cjAGks.jpg" alt=""></li>
    <li><img src="http://i.imgur.com/zA4lCs.jpg" alt=""></li>

  </ul>
    <ul>

        <li><img src="http://i.imgur.com/PuwwFs.jpg" alt=""></li>


    </ul>

Since you're already using jQuery the code could be simply

  if (photosLen > 1) {
      photos.each(function(i) {
          $(this).css('zIndex', i);
      })
      .parent()
      .addClass('album');
  }

Note the each() and the camelCase syntax for z-index property

You forget to increment the value of i in your code :

      while (i < photosLen) {

          $(this).children().css({
              'z-index': i
          });
          i++; 
      }

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