简体   繁体   English

使用 html 和 javascript 显示 json 文件中的多个数据“块”

[英]Display multiple “blocks” of data from json file using html and javascript

I have a JSON file with objects that have their own titles and other characteristics.我有一个 JSON 文件,其中的对象具有自己的标题和其他特征。 I'd like to use this data and append them as boxed elements in a page.我想将这些数据和 append 用作页面中的盒装元素。

I haven't figured out how to use a dynamic number of blocks of data (depending on the JSON file).我还没有弄清楚如何使用动态数量的数据块(取决于 JSON 文件)。

Any suggestions?有什么建议么?

today is a great day to learn about loops.今天是学习循环的好日子。 since you didn't give us any code, i'll make an example that will answer (in general) how to do this.因为你没有给我们任何代码,我会做一个例子来回答(通常)如何做到这一点。

<div id="demo">

</div>

<style>
    p {
        border: 2px solid black;
        width: 20%;
    }
</style>


<script>
 let object = {
     person1: {
         name: "bob",
         age: 30
     },
     person2: {
         name: "sherry",
         age: 35
     }
 }

let array = Object.keys(object);

Object.keys(object).forEach(function(key) {
    let name = object[key].name;
    let age = object[key].age;

    let p = document.createElement("P");
    let text = document.createTextNode(`name: ${name}, age: ${age}`);

    p.appendChild(text);
    document.getElementById("demo").appendChild(p);
});
</script>

since you didn't give an object (JSON) i made one up, but you can use this rough outline to style your own script around your data.因为您没有提供 object (JSON),所以我编了一个,但是您可以使用这个粗略的大纲来围绕您的数据设置自己的脚本样式。 However many name objects are in this object, thats how many times the code will run.然而,这个 object 中有许多名称对象,这就是代码将运行的次数。 so you could have 2, or 100, and each one will become its own box when the loop appends the element and the text to the document.所以你可以有 2 个或 100 个,当循环将元素和文本附加到文档时,每个都将成为自己的框。

hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM