首页 > 解决方案 > 在javascript中显示数组列表中的信息

问题描述

我有一个驱动程序名称列表,显示在我的页面上,当我单击该名称时,我想获得有关该驱动程序的更多信息。我正在努力运行一个函数。这是我的 html 的样子:

<main>
<nav id="list">

</nav>
<section id="profile">

</section>

那是我的清单:

const drivers = [{
  name: "data",
  age: "data1",
  nationality: "data2"
}]

这就是我要运行的功能:

function driverProfile(drivers) {
  const article = document.createElement('article');
  const span = document.createElement('span');
  const h2 = document.createElement('h2');

  h2.textContent = drivers[driver_id].nationality;
  span.textContent = drivers[driver_id].age;
  article.textContent = drivers[driver_id].name;
 }

 myProfile = driverProfile(drivers)
 profile.appendChild(myProfile)

我得到这个错误Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.指向profile.appendChild(myProfile)

我的列表功能:

drivers.forEach(addLink);

function addLink(driver, index) {
  const a = document.createElement('a');
  a.href = `?driver=${index}`;
  a.textContent = driver.name;
  list.appendChild(a);
}

标签: javascript

解决方案


对元素进行分组是更好的做法。首先在 div 中追加元素,然后将新的 div 追加到section

function driverProfile(drivers) {
  const div = document.createElement("div");
  const article = document.createElement('article');
  const span = document.createElement('span');
  const h2 = document.createElement('h2');

  h2.textContent = drivers[driver_id].nationality;
  span.textContent = drivers[driver_id].age;
  article.textContent = drivers[driver_id].name;
  div.appendChild(h2);
  div.appendChild(span);
  div.appendChild(article);
  return div;
 }

 myProfile = driverProfile(drivers);
 profile.appendChild(myProfile);

该程序给出错误,因为您的函数不是返回类型并且您正在将函数分配给myProfile变量。

appendChild函数将 html 元素作为对象,但你已经给出了函数。只需将函数更改为返回类型,如上面的代码所示。


推荐阅读