[英]Displaying information from an array list in 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);
}
对元素进行分组是更好的做法。 首先在 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 元素作为对象,但您已经给出了函数。 只需将函数更改为返回类型,如上面的代码所示。
driverProfile 没有返回任何节点。 在此函数结束时,您需要返回要附加的节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.