为什么只有最后一项显示,而不是全部显示

why is only the last item is showing and not all of them

本文关键字:显示 全部 一项 最后 为什么      更新时间:2023-09-26

我正在使用下面的代码调用一个显示所有产品的php页面,然后解析它们并将它们显示在字符串中。上周,它显示了所有结果,效果很好,但现在它似乎已经坏了,只显示数据库中的最后一个结果。在盯着屏幕看了几天和痛苦的一个小时后,我开始发疯了,需要一些帮助。

function display(results) {
    article = document.getElementById("homeArticle");
    item = '';
    for (var i = 0; i < results.length; i++){ 
        var item = results[i];
        var name = item.P_NAME;
        var description = item.P_DESCRIPTION;
        var price = item.P_PRICE;
            // next I add to the string that we want to place on the page
        item = '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
    };
    article.innerHTML = item;
}

function getItems() {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var results = JSON.parse(this.responseText);
        display(results.rows);
    };
    xhr.open("GET", "displayData.php");
    xhr.send();
}
window.addEventListener("load", getItems);

如果有人能提出任何有帮助的建议,非常感谢!

您需要两个变量。一个用于构建html字符串,另一个用于保存结果数组中的每个项。

将您的代码更改为:

function display(results) {
    article = document.getElementById("homeArticle");
    var html = '';
    for (var i = 0; i < results.length; i++){ 
        var item = results[i];
        var name = item.P_NAME;
        var description = item.P_DESCRIPTION;
        var price = item.P_PRICE;
            // next I add to the string that we want to place on the page
        html += '<section id="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';
    };
    article.innerHTML = html;
}

这样,您将附加html字符串,而不是覆盖前面的字符串。

还要考虑确保每个html元素都有一个唯一的id,可以通过在id后面加i来实现,例如

html += '<section id="homePageSection-'+i+'"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';

合并item字符串,不要使用重复的ID,而是使用类:

item += '<section class="homePageSection"> <p>Name:' + name + '</p><p>Description:' + description + '</p><p>Price:' + price + '</p></section>';

您所做的是在每次迭代中覆盖item,这就是为什么您只得到最后一个。


更新

忘记提供我写的最后一句话的代码了。为了避免覆盖它,可以使用不同的变量(如另一个答案中所示),也可以直接分配值,而不创建不必要的变量,如下所示:

for (var i = 0; i < results.length; i++){ 
    item += '<section class="homePageSection"> <p>Name:' + 
            results[i].P_NAME + 
            '</p><p>Description:' + 
            results[i].P_DESCRIPTION + 
            '</p><p>Price:' + 
            results[i].P_PRICE + 
            '</p></section>';
}