javascript - 如何使用 jquery 每 x 秒显示 n 个 json 项目?

标签 javascript jquery

我有一个 JSON 对象 items,其中有几个项目,我想每 2 秒显示其中 2 个项目。我该怎么做呢?因此,它每隔几秒就会显示 division1 中的项目,而不是一次显示所有项目。例如。每 5 秒获取所有项目,每秒显示 4 个项目,共 20 个项目。

<table id="division1" >
    <thead>
        <th>Name</th>
        <th>Score</th>
    </thead>
    <tbody></tbody>
</table>



function render_items(division){
    var tablebody ="";
        $.each(division.items, function (i,item){
            var tablerow ="<tr>"
                +"<td>"+item.name+"</td>"
                +"<td>"+item.score+"</td>"
                +"</tr>";
            tablebody = tablebody+tablerow;
            
           //$('#test').append(division.name+' '+i+' '+robot.name+'<br>');
        }
        );
        $('#'+division.name+" tbody").html(tablebody);  
}

function poll(){
    $.post("data.php", {getvalues: 0}, 
    function (data, status){
        $.each (data.divisions, function(i,division){
            render_items(division);     
            
        }); 
    },
    'json'
    );
    setTimeout('poll()',5000);
}

$(document).ready(function() {
    poll();
     
}

最佳答案

最简单的方法可能是隐藏所有行,然后每秒显示一系列行,如下所示:

function startShow(table) {
    var index = 0;
    var trs = table.find("tbody tr");
    function update() {
        if (index >= trs.length) {
            index = 0;
        }
        trs.hide().slice(index, index + 4).show();
        index += 4;
        setTimeout(update, 1000);
    }
    update();
}

然后用

调用它
startShow($("#division1"));

关于javascript - 如何使用 jquery 每 x 秒显示 n 个 json 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/665022/

相关文章:

javascript - 如何用JS手动弹出所需的文本字段警报?

jquery - 降低 jquery UI 中 Accordion 的速度

单击任何超链接时打开特定 URL 的 JavaScript

javascript - 将值设置为 getElementsByName 数组

javascript - 在客户端对 html 表列进行排序,无需除 jquery 之外的第三方

javascript - 如果元素高度大于 x addClass "portrait"否则 addClass "landscape"

jquery - IE 卡在 js 错误上

javascript - 将数据追加到一个数组中,而不是使用多嵌套数组

javascript - 在水平进度条上 Bootstrap 多个条

javascript - 为什么我应该将此 http 调用移至外部服务