我對JavaScript比較陌生,但決定將圖書館網站作爲我的第一個項目。在製作上述項目時,我試圖通過數組中的值設置innerHTML時遇到了錯誤。這是我(亂)代碼:(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部分是從哪裏獲得我的錯誤,指出「類型錯誤:無法設置屬性未定義‘的innerHTML’」。但是,我使用了警報功能,並獲得了目錄[0](Lost in the Woods)中的值。也似乎代碼可能只會在第一次循環後失敗,因爲我只是在第一次通過時才正常工作。我認爲這可能是innerHTML完全導致問題的原因,因爲當我註釋掉部分A時,部分B似乎具有相同的錯誤。 請幫我弄清楚這個錯誤,還有(因爲我是初學者,對本網站和Javascript都有幫助),告訴我如何從更好的角度來處理這個問題。並且請保持答案對初學者友好(如果可以的話)
你的while循環條件是'x
這裏是[SoloLearn](https://code.sololearn.com/WpZyzqUe11A5)上的鏈接 – SirLucidus
嘗試使用'innerText' –