我有一个映射的对象数组。我想将其附加到我的html文件中的无序列表中。这是我目前正在尝试做的事情。我收到此错误“ Uncaught TypeError:无法读取null的属性'appendChild'。
var newWorkArray= works.map(function(work){
return {
name : work.name,
title : work.title,
pic : work.pic,
link : work.link,
github : work.github
};
});
console.log("newArray", newWorkArray);
const workLiTag= document.createElement("li")
const workItem= document.createTextNode(newWorkArray)
workLiTag.appendChild(workItem)
document.getElementById("#work-items").appendChild(workItem)
我认为这不是必需的,但我将添加对象数组
var works = [
{
name:"Lorem Ipsum",
title: "Lorem Ipsum",
pic: "Lorem Ipsum",
link: "Lorem Ipsum",
github:"Lorem Ipsum"
},
{
name:"Ruby on Rails | Vue",
title: "Project Manager",
pic: "Lorem Ipsum",
link:"Lorem Ipsum",
github:"Lorem Ipsum"
},
答案 0 :(得分:1)
您忘了循环遍历新映射的数组。即使没有,.getElementById
也会接受目标元素本身的ID,而不是类似于.querySelector
的选择器。我改用后者。 .createTextNode
尝试创建javascript对象的文本,这是错误的,如果确实需要将整个对象显示为文本,则需要先使用JSON.stringify
对对象进行字符串化。
var works = [
{
name:"Lorem Ipsum",
title: "Lorem Ipsum",
pic: "Lorem Ipsum",
link: "Lorem Ipsum",
github:"Lorem Ipsum"
},
{
name:"Ruby on Rails | Vue",
title: "Project Manager",
pic: "Lorem Ipsum",
link:"Lorem Ipsum",
github:"Lorem Ipsum"
}
];
var newWorkArray = works.map(function(work){
return {
name : work.name,
title : work.title,
pic : work.pic,
link : work.link,
github : work.github
};
});
newWorkArray.forEach(function(i){
const workLiTag = document.createElement("li");
workLiTag.textContent = JSON.stringify(i);
document.querySelector("#work-items").appendChild(workLiTag);
})
<ul id="work-items"></ul>
我也不明白如果输出实际上是相同的,为什么必须映射原始数组。但是我只是假设您留下了这个细节,以便使问题更简单明了。否则,我会忘记使用.map()
创建新数组,因为您实际上并没有做任何事情。