【发布时间】:2021-01-19 04:02:00
【问题描述】:
我正在处理一个简单的库项目,其中您有一个对象数组,并通过使用我制作的 Book 构造函数创建书籍对象来填充它。
我能够找到一种方法来制作一个显示当前在数组中的书籍的函数,甚至能够制作一个按钮作为行中的最后一个子元素。该按钮目前不执行任何操作,但我希望它在单击时将“未读”状态更新为“已读”。
我向 Book 构造函数添加了一个原型,以便所有书籍都具有将其 read 属性更改为“read”、清除表并调用 displayBooks 函数的函数,以便表现在显示更新的信息。
当我在控制台中将它称为 book.readStatus();但是无论我在哪里尝试将事件监听器添加到按钮,它都会在代码中产生错误。
我认为最好的方法是向按钮添加一个事件监听器,这样它就可以改变它上面的孩子,但无法弄清楚那个部分。如果有更好的方法来获取更新按钮来更改读取状态,那也很棒。
代码如下:
let myLibrary = [];
// Constructor
function Book(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = "unread";
this.button = document.createElement('button');
}
Book.prototype.readStatus = function() {
this.read = "read";
clearTable();
displayBooks();
};
// Function to add to Libaray Array
function addBookToLibrary(obj) {
myLibrary.push(obj);
}
const imHappyForYou = new Book("I'm Happy for you", "Kay Wills Wyma", 231);
const theHobbit = new Book("The Hobbit", "JRR Tolkien", 298);
const crazyRichAsians = new Book("Crazy Rich Asians", "Kevin Kwan", 576);
addBookToLibrary(imHappyForYou);
addBookToLibrary(theHobbit);
addBookToLibrary(crazyRichAsians);
// var table = document.getElementById("table"); // set to table
let myTable = document.querySelector('#table');
let headers = ['Title', 'Author', 'Pages', 'Read/Unread', 'Update Read Status'];
function displayBooks() {
let table = document.createElement('table');
let headerRow = document.createElement('tr');
headers.forEach(headerText => {
let header = document.createElement('th');
let textNode = document.createTextNode(headerText);
header.appendChild(textNode);
headerRow.appendChild(header);
});
table.appendChild(headerRow);
myLibrary.forEach(book => {
let row = document.createElement('tr');
Object.values(book).forEach(text =>{
if(text == book.button) {
let cell = document.createElement('td');
let makeButton = document.createElement('button');
makeButton.innerHTML = "Update";
cell.appendChild(makeButton);
row.appendChild(cell);
} else {
let cell = document.createElement('td');
let textNode = document.createTextNode(text);
cell.appendChild(textNode);
row.appendChild(cell);
}
});
table.appendChild(row);
});
myTable.appendChild(table);
}
displayBooks();
let clearTable = function() {
const table = document.getElementById('table');
table.innerHTML = '';
}
【问题讨论】:
标签: javascript arrays object html-table prototype