【问题标题】:How to load html elements dynamically based upon input json?如何根据输入的json动态加载html元素?
【发布时间】:2019-03-12 08:24:43
【问题描述】:

如何遍历对象的输入数组?

目前仅包含 2 个人信息。但是输入的是50多人的信息,需要循环遍历所有的人。

示例代码:

const json = [
  {
    _id: "5af5cf0270d455a211200d4c",
    isActive: true,
    balance: "$3,507.97",
    picture: "http://placehold.it/32x32",
    age: 24,
    eyeColor: "brown",
    name: "Ahmed",
    gender: "male",
    company: "ATW",
    email: "atw@atw.com",
    phone: "+1 98908098",
    address: "661 Terrace Place, Elliott, Ohio, 9927",
    about:
      "Id sint labore sint dolore ex laboris. Ea irure dolor est nulla laboris Lorem sint fugiat laborum officia commodo. Reprehenderit culpa non voluptate ea. Fugiat duis et deserunt ea enim et ipsum nostrud commodo quis quis laborum officia. Elit est anim quis deserunt nulla nostrud ea eiusmod quis adipisicing. Mollit exercitation officia ipsum ea aliqua amet aliqua esse amet minim. Ipsum quis cillum fugiat reprehenderit sit aliquip aute in excepteur dolore fugiat esse non non.\r\n",
    registered: "2014-12-10T07:18:10 +02:00",
    latitude: -84.359436,
    longitude: 156.008804,
    tags: [
      "excepteur",
      "eiusmod",
      "laboris",
      "fugiat",
      "minim",
      "dolor",
      "qui"
    ],
    friends: [
      {
        id: 0,
        name: "Shields Terrell"
      },
      {
        id: 1,
        name: "Hilary Bruce"
      },
      {
        id: 2,
        name: "Lorraine Torres"
      }
    ]
  },
  {
    _id: "5af5cf0254f91fa2d555e1ae",
    isActive: false,
    balance: "$2,219.42",
    picture: "http://placehold.it/32x32",
    age: 27,
    eyeColor: "blue",
    name: "Maisa",
    gender: "female",
    company: "INTERFIND",
    email: "aqr@qra.com",
    phone: "+1 9780989080980",
    address: "595 Foster Avenue, Villarreal, Massachusetts, 4604",
    about:
      "Nostrud exercitation ea enim in consequat voluptate sint et laboris laborum elit nisi veniam. Do consectetur magna eiusmod anim nisi id sint consequat. Amet duis proident nisi excepteur. Reprehenderit non amet occaecat deserunt. Duis voluptate non in ex esse sit nostrud esse fugiat laboris fugiat qui reprehenderit.\r\n",
    registered: "2015-07-08T01:24:50 +03:00",
    latitude: -38.471736,
    longitude: -158.491974,
    tags: ["mollit", "minim", "duis", "anim", "aute", "magna", "ut"],
    friends: [
      {
        id: 0,
        name: "Dina Berger"
      },
      {
        id: 1,
        name: "Carmella Mckinney"
      },
      {
        id: 2,
        name: "Campbell Wooten"
      }
    ]
  }
];


document.getElementById("name").innerHTML = `${json[0].name}`;
document.getElementById("fullname").innerHTML = `${json[0].name}`;
document.getElementById("gender").innerHTML = `${json[0].gender}`;
document.getElementById("phone").innerHTML = `${json[0].phone}`;
document.getElementById("company").innerHTML = `${json[0].company}`;
document.getElementById("address").innerHTML = `${json[0].address}`;
document.getElementById("about").innerHTML = `${json[0].about}`;
document.getElementById("registered").innerHTML = `${json[0].registered}`;

HTML:

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Employee's Page</title>
    <link rel="stylesheet" href="./assets/css/style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
        crossorigin="anonymous">
</head>

<body>
    <h1><span id="name"></span></h1>
    <div class="container" style="border:1px solid #cecece;">

        <div class="flexcontainer">
            <div>
                <img src="" alt="Employee's Picture" id="picture">
            </div>
            <div>
                <ul>
                    <li>
                        <h3>Full name: <span id="fullname"></span></h3>
                    </li>
                    <li>
                        <h3>Gender: <span id="gender"></span></h3>
                    </li>
                    <li>
                        <h3>Phone number: <span id="phone"></span></h3>
                    </li>
                    <li>
                        <h3>Company: <span id="company"></span></h3>
                    </li>
                    <li>
                        <h3>Address: <span id="address"></span></h3>
                    </li>
                </ul>
            </div>
        </div>

        <div>
            <h3>About employee:</h3>
            <p><span id="about"></span></p>
        </div>

        <div>
            <h3>Employee was registered in the system: <span id="registered"></span></h3>
        </div>

    </div>
</body>
<script src="./assets/js/jsonlast.js"></script>



</html>

HTML(在我的问题中)页面连接到另一个页面,其中包含一个包含 json 文件中所有人员姓名的表格。需要的是,每当单击表格中的 name 时,它应该带我到 employee.html(我在我的问题中包含的 html 页面)但带有该人的信息。

【问题讨论】:

  • 不太清楚你在问什么。此外,表达式`${json[0].name}` 等价于json[0].name
  • 动态改变数据是什么意思?
  • 您是否打算循环遍历 JSON 并更新 innerHTML?
  • @DaltonWhyte 是的,这正是我们想要做的事情
  • @rm 和 happyKoala,我确实编辑了我的帖子。你能检查一下吗?

标签: javascript jquery html json ecmascript-6


【解决方案1】:

如果您可以使用 EMCAScript 5,您可以使用它来循环您的 json[0] 对象。

Object.keys(json[0]).forEach(function(key) {
    var el = document.getElementById(key);
    var isImg = (el.nodeName.toLowerCase() === 'img');
    if (isImg) el.src = json[0][key];
    else el.innerHTML = json[0][key];
});

【讨论】:

  • ID 属性的某些值与json 中对象的属性不完全匹配,例如#image 元素和json[0].picture 值。我认为这个解决方案是相反的:它增加了更多的模糊性并促进了错误。 ?
【解决方案2】:

我假设您想要循环遍历 JSON 并更新各个元素的 innerHTML。下面的代码可以帮助您实现这一点,但请注意,您必须确保您的 HTML 元素名称必须与 JSON 属性的名称匹配。前任。此代码不适用于:

document.getElementById("image").src = `${json[0].picture}`;

应该是:

document.getElementById("picture").src = `${json[0].picture}`;

因此,在使用解决方案之前,请将您的图像元素更新为:

<img src="" id="picture" />

为了显示多人使用这个解决方案,我添加了两个循环,外部循环将遍历每个人的记录:

将您的&lt;ul&gt;...&lt;/ul&gt; 修改为&lt;ul id="personList"&gt;...&lt;/ul&gt;

const json = [
  {
    _id: "5af5cf0270d455a211200d4c",
    isActive: true,
    balance: "$3,507.97",
    picture: "http://placehold.it/32x32",
    age: 24,
    eyeColor: "brown",
    name: "Ahmed",
    gender: "male",
    company: "ATW",
    email: "atw@atw.com",
    phone: "+1 98908098",
    address: "661 Terrace Place, Elliott, Ohio, 9927",
    about:
      "Id sint labore sint dolore ex laboris. Ea irure dolor est nulla laboris Lorem sint fugiat laborum officia commodo. Reprehenderit culpa non voluptate ea. Fugiat duis et deserunt ea enim et ipsum nostrud commodo quis quis laborum officia. Elit est anim quis deserunt nulla nostrud ea eiusmod quis adipisicing. Mollit exercitation officia ipsum ea aliqua amet aliqua esse amet minim. Ipsum quis cillum fugiat reprehenderit sit aliquip aute in excepteur dolore fugiat esse non non.\r\n",
    registered: "2014-12-10T07:18:10 +02:00",
    latitude: -84.359436,
    longitude: 156.008804,
    tags: [
      "excepteur",
      "eiusmod",
      "laboris",
      "fugiat",
      "minim",
      "dolor",
      "qui"
    ],
    friends: [
      {
        id: 0,
        name: "Shields Terrell"
      },
      {
        id: 1,
        name: "Hilary Bruce"
      },
      {
        id: 2,
        name: "Lorraine Torres"
      }
    ]
      },
      {
    _id: "5af5cf0254f91fa2d555e1ae",
    isActive: false,
    balance: "$2,219.42",
    picture: "http://placehold.it/32x32",
    age: 27,
    eyeColor: "blue",
    name: "Maisa",
    gender: "female",
    company: "INTERFIND",
    email: "aqr@qra.com",
    phone: "+1 9780989080980",
    address: "595 Foster Avenue, Villarreal, Massachusetts, 4604",
    about:
      "Nostrud exercitation ea enim in consequat voluptate sint et laboris laborum elit nisi veniam. Do consectetur magna eiusmod anim nisi id sint consequat. Amet duis proident nisi excepteur. Reprehenderit non amet occaecat deserunt. Duis voluptate non in ex esse sit nostrud esse fugiat laboris fugiat qui reprehenderit.\r\n",
    registered: "2015-07-08T01:24:50 +03:00",
    latitude: -38.471736,
    longitude: -158.491974,
    tags: ["mollit", "minim", "duis", "anim", "aute", "magna", "ut"],
    friends: [
      {
        id: 0,
        name: "Dina Berger"
      },
      {
        id: 1,
        name: "Carmella Mckinney"
      },
      {
        id: 2,
        name: "Campbell Wooten"
      }
    ]
  }
];

let i = 1;
for(var key in json[i]){
  if(key === "picture"){
    document.getElementById(key).src = json[i][key];
  } else {
    let spanElement = document.getElementById(key);
    if (spanElement){
      spanElement.innerHTML = json[i][key];
    }
  }
}
<div class="flexcontainer">
    <div>
        <img src="" alt="Employee's Picture" id="picture">
    </div>
    <div>
        <ul>
          <li>
              <h3>Full name: <span id="name"></span></h3>
          </li>
          <li>
              <h3>Gender: <span id="gender"></span></h3>
          </li>
          <li>
              <h3>Phone number: <span id="phone"></span></h3>
          </li>
          <li>
              <h3>Company: <span id="company"></span></h3>
          </li>
          <li>
              <h3>Address: <span id="address"></span></h3>
          </li>
        </ul>
    </div>
</div>

【讨论】:

  • 我现在试试,结果告诉你
  • 当然@AhmedHaiba 不要忘记将图像 HTML 元素的 id 属性从 id="image" 更新为 id="picture"
  • 我尝试了以下代码,但我认为我做的不对:document.getElementById("name").innerHTML = ${json[0].name}; document.getElementById("图片").src = ${json[0].picture}; document.getElementById("gender").innerHTML = ${json[0].gender}; for (var i in json) { for (var key in json[i]) { if (document.getElementById(key).nodeName.toLowerCase() === "img") document.getElementById(key).src = json [i][键];否则 document.getElementById(key).innerHTML = json[i][key]; } }
  • 你不需要这个代码:document.getElementById("name").innerHTML = ${json[0].name}; document.getElementById("picture").src = ${json[0].picture}; document.getElementById("gender").innerHTML = ${json[0].gender};
  • 使用给出的代码解决方案即可。注意使用json[0]只处理一个人记录
【解决方案3】:

试试JSON.parse(),这是一个内置函数,可以将json格式转换为javascript对象。然后你可以使用这个对象来改变你的内容。例如:

let JSON_object = "{\"name\": \"willem\", \"fullname\": \"van der Veen\" }"

const parsedObj = JSON.parse(JSON_object)

document.getElementById("name").innerHTML = parsedObj.name;
document.getElementById("fullname").innerHTML = parsedObj.fullname;
<div id="name">random</div>
<div id="fullname">random</div>

【讨论】:

  • 感谢您的代码,但它适用于所有人吗?因为json文件里有50多人
  • 只要在JSON中,就可以使用JSON.parse解析成JS对象。然后你可能想使用 for 循环来遍历元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2023-03-20
  • 2019-12-11
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
相关资源
最近更新 更多