使用下划线一个接一个地替换每个项目(li)

fadein each item (li) one after another using underscore

本文关键字:一个 li 替换 项目 下划线      更新时间:2024-06-29

我使用下划线显示JSON文件中<li>项的列表,与其一次显示所有项,不如一个接一个地淡入。我怎样才能做到这一点?

for (var j=0; j<rc.length; j++) {

%> 
<ul>
  <li class="productTile" data-id="<%= rc[j].id %>">
    <img src="<%= image %>" alt=""/>
    <h3>Demo<%= rc[j]["name"] %></h3>
    <p><%= rc[j].price.formatted %></p>
  </li>
</ul>
<%
                }  
                           };
%>

当循环时,要一个接一个地显示li元素,只需设置一个递增的超时:

var delay = 500;
for (var j=0; j<rc.length; j++) {
    setTimeout(function(){
      //fadeIn my <li>
    }, delay*j)
}

使用display: none样式一次创建所有div,然后使用库async编写以下内容:

// an array with all the ids
var ids = [...list of li ids...];
// handy async iterator
async.eachSeries(ids, fadeIdIterator, function(err){
  if(err){
    console.log('Something gone wrong');
  }
});
// this function will do the job for each element
function fadeInIterator(id, next){
  $('#'+id).fadeIn('slow', next);
}

您也可以使用jQuery编写所有内容,但使用此库编写异步内容要容易得多。

只是为了给出一个仅underscore的替代方案:

function fadeInIterator(id){
  return function(next) { $('#'+id).fadeIn('slow', next); };
}
// an array with all the ids
var ids = [...list of li ids...];
// this array will hold the callbacks
var fades = _.map(ids, function(id){  return fadeInIterator(id); });
_(fades).reduceRight(_.wrap, function() { console.warn('done') })();

对于underscore异步替代方案,我在这里查看了