首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在本地存储中删除错误的项目

在本地存储中删除错误的项目
EN

Stack Overflow用户
提问于 2021-11-01 18:16:51
回答 1查看 39关注 0票数 0

我正在尝试使用本地存储来为图书馆应用程序存储图书。我正在尝试实现删除功能,但遇到了问题。当我单击UI中的按钮删除条目时,它会从本地存储中删除随机的图书,而不是我要删除的单个图书。在UI中,正确的图书被删除,但在本地存储中,它的行为与我预期的不同。如果能得到任何帮助,我将不胜感激。下面是我的代码:

代码语言:javascript
复制
// Book Class
class Book {
    constructor(title, author, pages, bookRead) {
        this.title = title;
        this.author = author; 
        this.pages = pages;
        this.bookRead = bookRead;
    }
}

//Library Class
class Library {
    static showBook = () => {
        const bookList = UserStorage.getBooks();

        bookList.forEach((book) => Library.addBook(book))
    }
    static addBook = (book) => {
        const displayArea = document.querySelector('.displayArea');
        let newBook = document.createElement('div');
        newBook.classList.add('newEntry');

        let newTitle = document.createElement('div')
        newTitle.classList.add('newTitle', 'cardItem');
        newBook.appendChild(newTitle);
        newTitle.textContent = `Title: ${book.title}`

        let newAuthor = document.createElement('div')
        newAuthor.classList.add('newAuthor', 'cardItem');
        newBook.appendChild(newAuthor);
        newAuthor.textContent = `Author: ${book.author}`
        
        let newPages = document.createElement('div')
        newPages.classList.add('newPages', 'cardItem');
        newPages.textContent = `Pages: ${book.pages}`
        newBook.appendChild(newPages);

        const bookRead = document.querySelector('.hasRead').checked;
        let readSection = document.createElement('button')
        readSection.classList.add('readToggle')
        if(bookRead == true){
            readSection.textContent = 'Read';
        } else {
            readSection.textContent = 'Not Read';
        }
        newBook.appendChild(readSection);

        const deleteBtn = document.createElement('button');
        deleteBtn.classList.add('deleteBtn');
        deleteBtn.textContent = 'X';
        newBook.appendChild(deleteBtn);

        displayArea.appendChild(newBook); 
    }
    static clearInput = () => {
        document.querySelector('.title').value = '';
        document.querySelector('.author').value = '';
        document.querySelector('.pages').value = '';
        document.querySelector('.hasRead').value = '';
    }

    static deleteBook = (item) => {
        if(item.classList.contains('deleteBtn')) {
            item.parentElement.remove() 
        }
    }
    static toggleBookRead = (button) => {
        if(button.classList.contains('readToggle')) {
            if(button.textContent === 'Read') {
                button.textContent = 'Not Read'
            } else if (button.textContent === 'Not Read') {
                button.textContent = 'Read'
            }
        }
    }
}

// Local Storage Class
class UserStorage {
    static getBooks = () => {
        let booksInStorage;

        if(localStorage.getItem('booksInStorage') === null) {
            booksInStorage = [];
        } else {
            booksInStorage = JSON.parse(localStorage.getItem('booksInStorage'));
        }
        return booksInStorage;
    }
    static addBook = (book) => {
        const currentBookList = UserStorage.getBooks();
        currentBookList.push(book);
        localStorage.setItem('booksInStorage', JSON.stringify(currentBookList));
    }
    static removeBook = (title) => {
        const currentBookList = UserStorage.getBooks();
        currentBookList.forEach((book, index) => {
            if(title === title) {
                currentBookList.splice(index, 1);
            }
        })
        localStorage.setItem('booksInStorage', JSON.stringify(currentBookList));
    }
}

// Display book in library
document.addEventListener('DOMContentLoaded', Library.showBook)

// Toggle Add Button
const addButton = document.querySelector('.addBtn');
addButton.addEventListener('click', () => {
    addButton.style.display = 'none';
    document.querySelector('.addBook').style.display = 'block';
})

// Close Form Button
const closeBtn = document.querySelector('.closeBtn');
closeBtn.addEventListener('click', () => {
    document.querySelector('.addBook').style.display = 'none';
    addButton.style.display = 'block';
})

// Add book
document.querySelector('.submitBook').addEventListener('click', (e) => {
    e.preventDefault();
    const title = document.querySelector('[data-title]').value;
    const author = document.querySelector('[data-author]').value;
    const pages = document.querySelector('[data-pages]').value;
    const bookRead = document.querySelector('.hasRead').checked;

    const book = new Book(title, author, pages, bookRead)

    // Add Book to UI
    Library.addBook(book)

    // Add Book to Local Storage
    UserStorage.addBook(book); 

    // Clear Input Fields
    Library.clearInput();
})


// Delete Book
document.querySelector('.displayArea').addEventListener('click', (e) => {
    e.preventDefault();
    Library.deleteBook(e.target);
    console.log(e.target.parentElement.firstChild)
    UserStorage.removeBook(`${e.target.parentElement.textContent}`)
})

// Mark book as Read/Not Read
document.querySelector('.displayArea').addEventListener('click', (e) => {
    e.preventDefault();
    Library.toggleBookRead(e.target);
})
代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Library App</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <img class="leftImg" src="Images/pile_of_books.png" alt="Image of Books"><h1 class="mainTitle">My Library</h1><img class="rightImg" src="Images/pile_of_books.png" alt="Image of Books">
    </header>
    <main>
        <section>
            <div class="mainContent">
                <h2 class="libraryTitle">Would you like to add a book to your library?</h2>
                <button class="addBtn">Add</button>
                <div class="addBook">
                    <form class="newBookForm">
                        <button class="closeBtn">X</button>
                        <input data-title class="title" type="text" placeholder="Title">
                        <input data-author class="author" type="text" placeholder="Author">
                        <input  data-pages class="pages" type="number" placeholder="Pages">
                        <label class="readSection" for="hasRead">
                            <label class="readTitle">Have you read this book?</label>
                            <input class="hasRead" type="checkbox">
                        </label>
                        <button class="submitBook">Submit book?</button> 
                    </form>
                </div>
            </div>
            <div class="displayArea">
    
            </div>
        </section>
        
    </main>
    <footer>

    </footer>
    
</body>
<script src="script.js" defer></script>
</html>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-01 18:23:08

我认为你不应该从循环内部操作数组:

代码语言:javascript
复制
currentBookList.forEach((book, index) => {
            if(title === title) {
                currentBookList.splice(index, 1);
            }
        })

如果先找到索引,然后使用splice,哪种方法会更好:

代码语言:javascript
复制
let index = currentBookList.findIndex((book) => {
            if(title === book.title) 
        {         
             return true;
            }
        })

currentBookList.splice(index, 1);

此外,请使用book.title而不是title === title

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69801072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档