延迟循环中附加HTML的外观

时间:2014-12-21 01:53:45

标签: jquery html animation

我使用以下代码:

$.getJSON( "getData.php", function( data ) {
        var items = [];
        $.each( data, function( key, val ) {
            items.push( '<li id="' + key + '"><img width="230px" height="230px" src="' + val['imageURL'] + '" /><div><i class="fa fa-play-circle"></i>' + val['word'] + '</div></li>' );
        });


        $( "<ul/>", {
            "class": "vocab-list",
            html: items.join( "" )
        }).appendTo( ".lesson-body" );

    });

如何在页面上显示每个<li>时出现延迟?

1 个答案:

答案 0 :(得分:1)

这是一种做法。

您可以setTimeout显示延迟。您还可以使用closure来保持循环中的范围。

Here is more info about timing handlers

Here is more info about closure

Here is a fiddle to play with

var data = [],
  image = 'http://piq.codeus.net/static/media/userpics/piq_38546_400x400.png',
  Handlers = {
    ProcessData: function($list, key, val, count) {
      //use a timeout to create the delay you're looking for.  
      //Remember, when our timeout runs we get access to local variables, the containers 
      //variables and any global variables.  This is how we can maintain our variables throughout 
      //the loop, otherwise the key wouldn't be what you want it to be.
      setTimeout(function() {
        $list.append('<li id="' + key + '">' +
          '<img width="100px" height="100px" src="' + val['imageURL'] + '" />' +
          '<div>' +
          '<i class="fa fa-play-circle"></i>' +
          val['word'] +
          " ID is " + key +
          '</div>' +
          '</li>');
      }, count * 500);
    },
    DoCallback: function(data) {
      var $list = $('.lesson-body').append('<ul class="vocab-list" />').find('.vocab-list'),
          count = 0;
      $.each(data, function(key, val) {
        //loop through the data, calling this function to preserve our variables
        Handlers.ProcessData($list, key, val, count++);
      });
    }
  }


//create mock data
data.push({
  'imageURL': image,
  'word': 'A'
});
data.push({
  'imageURL': image,
  'word': 'B'
});
data.push({
  'imageURL': image,
  'word': 'C'
});
data.push({
  'imageURL': image,
  'word': 'D'
});

//process the data
Handlers.DoCallback(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='lesson-body'>
</div>