javascript - $.each() jQuery 新闻源

标签 javascript jquery json

我正在尝试在我的网站上运行新闻源。它显示所有新闻并循环播放除过期新闻外的所有新闻。我可以通过网页添加新闻,因此 JSON 可能会不断变化。 PHP 脚本生成 JSON 如下:

[
    {
    "0": "Monsieur",
    "1": "X",
    "2": "24",
    "3": "236",
    "4": "Artichauts",
    "5": "4",
    "6": "2015-06-19",
    "7": "2015-06-26",
    "8": "9",
    "9": "7",
    "nom": "Monsieur",
    "prenom": "X",
    "id_promotion": "24",
    "id_commercant": "236",
    "article": "Artichauts",
    "rubrique": "4",
    "date_debut": "2015-06-19",
    "date_fin": "2015-06-26",
    "prix_origine": "9",
    "prix_promotion": "7"
},
{
    "0": "Monsieur",
    "1": "X",
    "2": "23",
    "3": "236",
    "4": "Betteraves",
    "5": "4",
    "6": "2015-06-18",
    "7": "2015-06-25",
    "8": "8",
    "9": "6",
    "nom": "Monsieur",
    "prenom": "X",
    "id_promotion": "23",
    "id_commercant": "236",
    "article": "Betteraves",
    "rubrique": "4",
    "date_debut": "2015-06-18",
    "date_fin": "2015-06-25",
    "prix_origine": "8",
    "prix_promotion": "6"
}
]

我的 jQuery 脚本正在(尝试)展示它们

$(document).ready(function () {
    function newsfeed() {
        $.getJSON("newsfeed.php", function (result) {
            var htmldata = "";
            $.each(result, function (key) {
                $("#news").html(result[key].nom + " " + result[key].prenom + " has a special offer : " + result[key].article + " at " + result[key].prix_promotion + "€ instead of " + result[key].prix_origine + "€ ").delay(5000).slideUp(300)
                    .delay(500)
                    .fadeIn(400);
            });
            x = setTimeout(function () {
                newsfeed()
            }, 5000);
        });
    }
    newsfeed();
});

所以这段代码不断输出

Monsieur X has a special offer : Betteraves at 6€ instead of 8€

所以我的问题是, $.each() 函数没有按我想要的方式工作。如果有人有想法,我将不胜感激。

最佳答案

循环内的

$("#news").html 正在用循环元素替换 #news 的全部内容。

each中创建所有html,并在完成循环后将其注入(inject)到div中。

    var htmldata = '' ;
    $.each(result, function(key){
        htmldata += result[key].nom + " " + result[key].prenom + " has a special offer : " + result[key].article + " at " + result[key].prix_promotion + "€ instead of " + result[key].prix_origine + "€ ";
    });
    $('#news').html(htmldata);

关于javascript - $.each() jQuery 新闻源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30934477/

相关文章:

javascript - jQuery:暂停按钮暂停所有其他操作

javascript - 使用 css 将按钮定位在 html 中的输入文本字段顶部时出现问题

javascript - 动态添加通过 json 创建的选择项

javascript - 根据缩放级别显示或隐藏 SVG 元素

javascript - 为键和值对构建一个 JSON 结构,其中每个项的键都会发生变化?

javascript - 更改谷歌图表中的数字格式

javascript - 对多个条件使用 if 语句与 switch case

jquery - 内容 slider (仍在移动)

javascript - 如何最初仅扩展此 d3.js 中选定的 Node ?

json - 来自 bash 脚本的 ARM.Template。未终止的字符串。预期的分隔符 :