You need to enable JavaScript to run this app. 使用JSON生成国家防疫政策卡片时仅显示长卡片而非独立卡片求助
优惠活动
大模型
产品
解决方案
定价
更多

使用JSON生成国家防疫政策卡片时仅显示长卡片而非独立卡片求助

问题原因

  • document.querySelector('.output') 只会匹配页面中第一个class为output的元素,你所有国家的数据都被追加到了第一个卡片的内容容器里,所以全部内容堆成了一个长卡片。
  • 你在HTML里写死了多组固定的column/card/output结构,没有和国家数据做对应,属于冗余结构。

修正方案

第一步:简化HTML结构

删掉多余的固定卡片结构,只保留外层的row容器,所有卡片由JS动态生成:

<!DOCTYPE html>
<html>
<head>
    <title>Sheet Data</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="row">
    <!-- 所有卡片都会动态插入到这里 -->
  </div>
  <script src="main.js"></script>
</body>
</html>

第二步:修改JS逻辑

循环每个国家数据时,先为它生成完整的column+card+output结构,再把国家信息填进去,最后追加到row容器里:

const url = '(the url to the json file)'
const row = document.querySelector('.row');
getData();

function getData() {
    fetch(url).then((res) => {
        return res.json()
    }).then((json) => {
        json.data.forEach(ele => {
            // 先为当前国家生成完整的卡片外层结构
            const column = document.createElement('div');
            column.className = 'column';
            const card = document.createElement('div');
            card.className = 'card';
            const output = document.createElement('div');
            output.className = 'output';

            // 原有内容生成逻辑不变,内容都追加到当前国家专属的output里
            const title = document.createElement('div');
            title.innerHTML = `<h1>${ele.country}</h1>`
            title.style.background = ele.maincolour
            title.style.textIndent = "20px"
            title.style.paddingTop = "1px"
            output.append(title);
            const img1 = document.createElement('img');
            img1.src = ele.pod;
            img1.style.width = "100%";
            title.append(img1);
            const body = document.createElement('div');
            body.innerHTML = `<b>Open For Tourists: </b><br>${ele.tourists}<br><br>
            <b>Vaccines Accepted:</b><br>${ele.vaccine}<br><br>
            <b>PCR Test: </b><br>${ele.pcr}<br><br>
            <b>Quarantine: </b><br>${ele.quarantine}<br><br>
            <b>Direct Flights: </b><br>${ele.directflights}`
            body.style.textIndent = "0px"
            body.style.fontFamily = 'Advent Pro, sans-serif'
            body.style.fontSize = "14px"
            body.style.paddingTop = "15px"
            body.style.paddingBottom = "20px"
            body.style.paddingLeft = "15px"
            title.append(body);

            // 把当前国家的卡片拼接到外层row容器里
            card.append(output);
            column.append(card);
            row.append(column);
        })
    });
}

修改后你原来的style.css里的row、column、card样式会自动生效,每个国家都会对应生成独立的卡片,不会再堆在一起。

内容的提问来源于stack exchange,提问作者Nathan Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:12:02