【发布时间】:2017-02-12 08:05:40
【问题描述】:
我对 Javascript 比较陌生,但我决定将图书馆网站作为我的第一个项目。在制作上述项目时,当我尝试通过数组中的值设置 innerHTML 时遇到了一个错误。这是我的(凌乱的)代码:
var catalog = [];
function book (title, firstName, lastName, number, publisher, image, checkedOut) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.publisher = publisher;
this.image = image;
this.isCheckedOut = checkedOut;
}
function addToCatalog (entry){
entry.number = catalog.length ;
catalog[entry.number] = entry;
}
$newbook = new book("Lost in the Woods", "Hubert", "Holmes", "3", "Junior Scholastic", "https://marketplace.canva.com/MAB5W63LDsw/1/0/thumbnail_large/canva-woods-thriller-e-book-cover-MAB5W63LDsw.jpg", false);
addToCatalog($newbook);
$newbook = new book("To Kill A Mockingbird", "Harper", "Lee", "1", "Junior Scholastic", "https://s-media-cache-ak0.pinimg.com/736x/a0/96/ff/a096ff3bafb7786b59ef9ba9d3e7ddf2.jpg", false);
addToCatalog($newbook);
var address = document.createElement("DIV");
address.setAttribute("class", "eachBook");
var picture = document.createElement("img");
picture.setAttribute("src", "http://www.iconsdb.com/icons/preview/gray/literature-xxl.png" );
picture.setAttribute("class", "bookImg");
picture.setAttribute("alt", "Auburn Library Book");
var gtitle = document.createElement("h4");
gtitle.setAttribute("class", "bTitle");
var dname = document.createElement("p");
dname.setAttribute("class", "bName");
var button = document.createElement("button");
button.setAttribute("class", "checkout");
checkout = document.createTextNode("Checkout");
button.appendChild(checkout);
//Text in button
var available = document.createElement("p");
available.setAttribute("class", "available");
avail = document.createTextNode("Available");
available.appendChild(avail);
//text in available
function createBooks(){
document.getElementById("displayBooks").appendChild(address);
address.appendChild(picture);
address.appendChild(gtitle);
address.appendChild(dname);
address.appendChild(button);
address.appendChild(available);
}
function write(){
var x = 0;
var arr;
while (x < catalog.length){
createBooks();
arr = document.getElementsByClassName("bTitle");
arr[x].innerHTML = catalog[x].title; //Part A
arr = document.getElementsByClassName("bName");
arr[x].innerHTML = catalog[x].firstName +" "+ catalog[x].lastName;//Part B
arr = document.getElementsByTagName("img");
arr[x].src = catalog[x].image;
x++;
}
}
window.onload = function(){
write();
};
在 A 部分,我收到错误消息“TypeError: Cannot set property 'innerHTML' of undefined”。但是,我使用了警报功能并获得了 catalog[0] 的值(迷失在树林中)。似乎代码可能只会在第一次通过循环后失败,因为我只能让它在第一次通过时才能正常工作。我认为这可能是 innerHTML 完全导致了问题,因为当我注释掉 A 部分时,B 部分似乎有同样的错误。 请帮我找出这个错误,并且(因为我是这个网站和 Javascript 的初学者),请告诉我如何从更好的角度解决这个问题。并且请保持答案对初学者友好(如果可以的话)
【问题讨论】:
-
你的while循环条件是
x < catalog.length,catalog.length不一定和arr.length一样,所以arr[x]有可能是未定义的 -
这是SoloLearn上的链接
-
尝试使用
innerText
标签: javascript html arrays innerhtml