【问题标题】:Change text Inside heading with info from Array使用数组中的信息更改文本内部标题
【发布时间】:2021-11-19 08:22:13
【问题描述】:

我正在调用 fetch 来检索球员卡上的一些数据。 我正在尝试显示所述卡片,但在准确解析 JSON 和在 HTML 中显示信息时遇到了问题。

以下是卡片的 HTML 标题示例:

<h3 class="card__title"><a href="item.html">Example Card</a></h3>

这是我在 fetch 调用后使用的一些 JavaScript 代码:

let cardList = json.results         
let cardTitle0 = cardList[0].name.toString();

如何从我的数组中更改示例卡片 -> cardTitle0 中的文本?此问题适用于数组和 HTML 对象的其他属性。

【问题讨论】:

    标签: javascript html arrays json


    【解决方案1】:

    您需要使用h3 元素来获取链接:

    const link = document.querySelector(".card__title a");
    
    // These can be const.
    const cardList = json.results         
    const cardTitle0 = cardList[0].name.toString();
    
    link.innerHTML = cardTitle0;
    

    对于多张卡片,您必须遍历 cardList json 结果以及页面上的元素。

    这只是我头脑中的一个想法,所以我无法验证此代码是否有效,甚至是解决多张卡的最佳选择,但希望它能让您朝着正确的方向前进。

    const links = document.querySelectorAll(".card__title a");
    
    const cardList = json.results;
    
    // Loop through the links on the page.
    for (let i = 0; i < links.length - 1; i++)
    {
        for (let j = 0; j < cardList.length - 1; j++)
        {
            const title = cardList[j].name.toString();
    
            links[i].innerHTML = title;
        }
    }
    

    【讨论】:

    • 谢谢,这适用于第一张卡...但所有其他卡也使用相同的 .card__title 类...我应该为每张卡更改它们吗?
    • 我更新了答案以说明要更新的卡片列表。至少应该让你开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多