2014-10-02 51 views
-1

我把这个AJAX调用给了一个XML文件,WOrks很好。 但我只想要项目2-6,而不是全部。 我该怎么做?只获得5个项目

$(xml).find('item').each(function(){ 

      var toplist_no = $(this).find('no').text(); 
      var toplist_user = $(this).find('user').text(); 
      var toplist_won = $(this).find('won').text(); 
      var toplist_loose = $(this).find('loose').text(); 

      $('#toplisttable_' + cno + ' tr:last').after('<tr><td>' + toplist_no + '(' + cno + ')</td><td>' + toplist_user + '</td><td>' + toplist_won + '-' + toplist_loose + '</td></tr>'); 

}); 

回答

2

你可能只是添加计数器?

var counter = 0; 
$(xml).find('item').each(function(){ 

    // skip first item 
    // or items beyond the fifth 

    if (counter == 0) { 
     counter++; // increase counter 
     continue; // skip everything after this statement 
    } 

    if (counter > 4) { 
     // larger then 4 
     // we can stop the loop here 
     break; 
    } 

    var toplist_no = $(this).find('no').text(); 
    var toplist_user = $(this).find('user').text(); 
    var toplist_won = $(this).find('won').text(); 
    var toplist_loose = $(this).find('loose').text(); 

    $('#toplisttable_' + cno + ' tr:last').after('<tr><td>' + toplist_no + '(' + cno + ')</td><td>' + toplist_user + '</td><td>' + toplist_won + '-' + toplist_loose + '</td></tr>'); 

    counter++; 

}); 
1

你可以指望像迭代:

k = 0; 

$(xml).find('item').each(function(){ 
    if(k <= 5){ 
     ...do your stuff 
    }else { 
     return false;//breaks the loop 
    } 
    k++; 
}); 
0

记:你没有定义额外的变量,在每()的回调函数,指数作为参数.each(function(i){...})