[英]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.