使用innerHTML在特定div中显示JSON/对象数据 [英] Using innerHTML to display JSON/object data in a certain div

查看:106
本文介绍了使用innerHTML在特定div中显示JSON/对象数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下JS代码.加载HTML文档后,脚本会正确显示三个位置数据集.

I have created the following JS code. When the HTML document loads, the script displays the three location data sets properly.

<html>
<head>
<title>Javascript Beginner</title>
</head>
<body>
<script>

pios ('a', '7886 Dublin Blvd', 'Dublin, ', 'CA ', '94568');
pios ('b', '1 Stoneridge Mall Space', 'Pleasanton, ', 'CA ', '94588');
pios ('c', '1120 Stoneridge Mall Drive', 'Pleasanton, ', 'CA ', '94566');

function pios(iID, Address, City, State, Zip)
{
   document.body.innerHTML +='<p id='+iID+'></p>';
   document.getElementById(iID).innerHTML = Address + '<br>' + City + State + Zip;
   
}	
</script>
</body>
</html>

现在让我失望了,我需要了解如何使这些数据显示在指定的div中,例如div id = whatever?现在它刚出现在体内.

Now that I got that down I need to understand how I can make this data appear within a specified div, like div id=whatever? Right now it just appears within the body.

此外,我知道这段代码很粗糙,因此想知道编写此代码的最佳方法是什么?

Also, I know this code is rough and thus, wonder what is the best way to write this?

推荐答案

更新

将pio数据存储在数组中并对其进行迭代看起来像这样.

Update

Storing the pio data in an array and iterating over it would look something like this.

var piosData = [{
  id: 'a',
  address: '7886 Dublin Blvd',
  city: 'Dublin, ',
  state: 'CA ',
  zip: '94568'
}, {
  id: 'b',
  address: '1 Stoneridge Mall Space',
  city: 'Pleasanton, ',
  state: 'CA ',
  zip: '94568'
}, {
  id: 'c',
  address: '1120 Stoneridge Mall Drive',
  city: 'Pleasanton, ',
  state: 'CA ',
  zip: '94568'
}];

piosData.forEach(function(pio) {
  pios(pio);
});

function pios(pio) {
  var div = document.createElement('div');
  div.setAttribute('id', pio.id);
  div.innerHTML = pio.address + '<br />' + pio.city + pio.state + pio.zip;
  document.body.appendChild(div);
}

您可以使用 document.createElement 创建任何类型的新元素,然后使用

function pios(iID, Address, City, State, Zip)
{
   var div = document.createElement('div');
   div.setAttribute('id', iID);
   div.innerHTML = Address + '<br />' + City + State + Zip;
   document.body.appendChild(div);   
}

var piosData = [{
  id: 'a',
  address: '7886 Dublin Blvd',
  city: 'Dublin, ',
  state: 'CA ',
  zip: '94568'
}, {
  id: 'b',
  address: '1 Stoneridge Mall Space',
  city: 'Pleasanton, ',
  state: 'CA ',
  zip: '94568'
}, {
  id: 'c',
  address: '1120 Stoneridge Mall Drive',
  city: 'Pleasanton, ',
  state: 'CA ',
  zip: '94568'
}];

piosData.forEach(function(pio) {
  pios(pio);
});

function pios(pio) {
  var div = document.createElement('div');
  div.setAttribute('id', pio.id);
  div.innerHTML = pio.address + '<br />' + pio.city + pio.state + pio.zip;
  document.body.appendChild(div);
}

这篇关于使用innerHTML在特定div中显示JSON/对象数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆