javascript - 在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 元素作为对象,但你已经给出了函数。只需将函数更改为返回类型,如上面的代码所示。
推荐阅读
- spring-boot - Spring Batch:无法为表中的标识列插入显式值
- python - 加载以前保存的没有自定义层的模型时缺少 get_config
- flutter - 变量名重复,一定有办法减少代码
- r - 格式化 R 中表的分组数据
- nginx - 如何在 nginx 中动态匹配 URL 位置
- twig - HTML 代码在 OpenCart 运输方法标签中不起作用
- java - 尝试使用 @Value 从属性文件设置 @Scheduled 的 cron 属性,但出现编译时错误
- flutter - 如何在颤动的字符串中使用特殊的unicode字符?
- c++ - 在 Windows 中创建 OpenGL 上下文
- symfony - 在不同的频道中发送 symfony ChatMessage