You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript从对象获取数据并赋值到HTML对应元素

方案1:展示指定单个人物的信息

如果你只需要展示某一个索引对应的人物数据,直接匹配属性和DOM id即可:

// 定义你要展示的人物索引,示例为0即Peter
const targetPersonIndex = 0;
const currentPerson = people[targetPersonIndex];

// 遍历人物的所有属性,自动匹配对应id的p标签赋值
for (const [propKey, propValue] of Object.entries(currentPerson)) {
  const targetDom = document.getElementById(propKey);
  // 校验DOM存在再赋值,避免报错
  if (targetDom) {
    targetDom.textContent = propValue;
  }
}

方案2:展示所有人物的信息

你现有的HTML结构只有一套p标签,无法承载多个人物数据,需要动态生成DOM节点:

const peopleWrapper = document.getElementById('people');
// 清空原有HTML内容
peopleWrapper.innerHTML = '';

// 遍历所有人的数据
Object.values(people).forEach(personItem => {
  // 为单个人物创建独立容器
  const personContainer = document.createElement('div');
  personContainer.style.margin = '12px 0';
  personContainer.style.paddingBottom = '12px';
  personContainer.style.borderBottom = '1px solid #eee';

  // 生成对应属性的p标签
  for (const [propKey, propValue] of Object.entries(personItem)) {
    const pTag = document.createElement('p');
    pTag.textContent = `${propKey}: ${propValue}`;
    personContainer.appendChild(pTag);
  }

  peopleWrapper.appendChild(personContainer);
});

核心逻辑说明

  • 你的people是键为连续数字的类数组对象,用Object.values()可以直接提取所有人物数据组成数组,简化遍历逻辑
  • 人物对象的属性名和你定义的p标签id完全对应,直接用属性名作为id查找DOM即可
  • 赋值优先用textContent而非innerHTML,避免XSS安全风险

内容的提问来源于stack exchange,提问作者duong-manh-dung

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:48:00