jQuery Live Feed仅显示10个项目

时间:2016-01-17 14:24:48

标签: javascript jquery html mysql

我最近找到this code snippet solution on 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秒后,它应该加载另一条新推文(如果有的话)。

如何添加此限制?

由于

1 个答案:

答案 0 :(得分:0)

<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