gpt4 book ai didi

javascript - 图书馆项目 - 图书移除时更新对象

转载 作者:行者123 更新时间:2023-11-30 13:54:57 24 4
gpt4 key购买 nike

问题:

当用户创建一本书时,将显示输入字段中的信息。有一个删除按钮,用户可以单击它来删除这本书。但是,当我使用 filter() 时,我只是返回 book 参数,那么我可以对 deleteBook() 进行哪些更改才能删除一本书?我不希望 UI 正常工作,但我只想更新库数组。

回复:https://repl.it/@antgotfan/library

我尝试过的:

我试过操纵文档,每当用户点击删除时,它就会被删除,但不会更新对象以显示它实际上已被删除

// Variables
const addBook = document.querySelector("#add");
let library = [];

// Event Listeners
addBook.addEventListener("click", render);
document.addEventListener("click", deleteBook);


// Constructor
function Book(title, author, pages, isRead) {
this.title = title;
this.author = author;
this.pages = pages;
this.isRead = isRead;
}

// Prototypes
Book.prototype.toggleIsRead = function() {
if (this.isRead == "Read") {
this.isRead = "Not read";
} else {
this.isRead = "Read";
}
}

function deleteBook(event) {
if (event.target.id == "remove") {
library.filter(book => {
return book;
});
}
}

// Functions
function addBookToLibrary() {
let authorOfBook = document.querySelector("#author").value;
let bookTitle = document.querySelector("#book-title").value;
let numberOfPages = document.querySelector("#pages").value;
let status = document.querySelector("#isRead").value;
let newBook = new Book(bookTitle, authorOfBook, numberOfPages, status);

library.push(newBook);

return newBook;
}

function updateStatus() {

}

function emptyInputs() {
const inputs = Array.from(document.querySelectorAll("input"));
inputs.forEach(input => input.value = "");
}

function render() {
addBookToLibrary();
emptyInputs();

let newBook = library[library.length - 1];
let table = document.querySelector("table");
let createTr = document.createElement("tr");

table.appendChild(createTr);
createTr.innerHTML = `<td>${newBook.title}</td>
<td>${newBook.author}</td>
<td>${newBook.pages}</td>
<td><button class="table-buttons" id="not-read">${newBook.isRead}</button></td>
<td><button class="table-buttons" id="remove">Delete</button></td>`;
}

错误信息:

没有错误,只是没有更新的对象来显示保留或删除的内容。

最佳答案

由于书籍在一个数组中,您可以使用一个函数来获取书籍属性,如作者、标题等然后使用该信息在数组中找到这本书并将其删除。

let books = [{ title: "book1" }, { title: "book2" }];

console.log(books);
deleteBook("book2");
console.log(books);

function deleteBook(title) {
let i = books.findIndex(b => b.title == title);
books.splice(i, 1);
}

//Outputs
[ { title: 'book1' }, { title: 'book2' } ] //before delete called
[ { title: 'book1' } ] //after delete called

关于javascript - 图书馆项目 - 图书移除时更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57487282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com