jQuery Live Feed 仅显示 10 个项目

jQuery Live Feed only display 10 items

本文关键字:项目 显示 Live Feed jQuery      更新时间:2023-09-26

我最近在stackoverflow上发现了这个代码片段解决方案。

.HTML

<html>
<head><title>Tweets</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#tweets {
    width: 500px;
    font-family: Helvetica, Arial, sans-serif;
}
#tweets li {
    background-color: #E5EECC;
    margin: 2px;
    list-style-type: none;
}
.author {
    font-weight: bold
}
.date {
    font-size: 10px;
}
</style>
<script>
jQuery(document).ready(function() {
    setInterval("showNewTweets()", 1000);
});
function showNewTweets() {
    $.getJSON("feed.php", null, function(data) {
        if (data != null) {
            $("#tweets").prepend($("<li><span class='"author'">" + data.author + "</span> " +  data.tweet + "<br /><span class='"date'">" + data.date + "</span></li>").fadeIn("slow"));
        }
    });
}
</script>

.PHP

<?php
echo json_encode(array( "author" => "someone",
                        "tweet" => "The time is: " . time(), 
                        "date" => date('l jS 'of F Y h:i:s A')));
?>

对我来说效果很好,但我希望它不断(每 3 秒)查看是否有新的推文可用,如果是这样,它应该将推文添加到列表顶部。该列表最多只能包含 10 个<li></li>项。如果有超过 1 条新推文,它应该只添加 1 条新推文,再过 3 秒,它应该加载另一条新推文(如果可用)。

如何添加此限制?

谢谢

<script>
jQuery(document).ready(function() {
    setInterval("showNewTweets()", 1000);
});
function showNewTweets() {
    var tweets = 0;
    $("#tweets").html('');
    $.getJSON("feed.php", null, function(data) {
        if (data != null || tweets <= 10) {
            $("#tweets").prepend($("<li><span class='"author'">" + data.author + "</span> " +  data.tweet + "<br /><span class='"date'">" + data.date + "</span></li>").fadeIn("slow"));
            tweets++;
        }
    });
}
</script>

清空列表并使用某种计数器仅添加最后 10 条推文。代码执行将在第 10 条推文或没有要显示的推文时停止。

此外,在生成数组的 PHP 代码中,您可能希望在对数组进行编码之前array_flip它。