无法从Localstorage获取信息 - JavaScript

时间:2017-01-26 02:41:24

标签: javascript jquery local-storage

我正在学习如何在JavaScript中使用localstorage,所以我创建了一个应用程序来进行练习。当我运行代码时,它给了我这个错误:

ERROR

我把html和css放在codepen上,这里是链接: Link To Code

JavaScript代码

// READY
$(document).ready(() => {
    // when user clicks on submit
    $(".submit").on("click", addItem);

    // show bookmarks
    showBookmarks();
})

// ADD ITEM
let addItem = (e) => {
    // get values from inputs
    let name = $(".name").val();
    let link = $(".url").val();

    // stores bookmarks
    let bookmark = {
        name: name,
        url: link
    };

    // bookmark varification
    // if theres nothing in bookmarks
    if(localStorage.getItem("bookmarks") == null) {
        // init array
        let bookmarks = [];
        // add to array
        bookmarks.push(bookmark);
        // set to local storage
        localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
    } else { // if theres something in bookmarks
        // get from local storage
        let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
        // add bookmark to array
        bookmarks.push(bookmark);
        // reset back to local storage
        localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
    }

    // prevent form from submitting
    e.preventDefault();
}

// SHOW BOOKMARKS
let showBookmarks = () => {
    // get from local storage
    let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));

    // loop through local storage data
    for(let i = 0; i < bookmarks.length; i++) {
        let name = bookmarks.name[i];
        let url = bookmarks.url[i];

        // append bookmarks
        $(".show").append(`
            <div class="bookmarks-container">
                <div class="bookmark">
                    <a href="${url}" target="_blank">${name}</a>
                    <i class="fa fa-trash fa-lg" aria-hidden="true"></i>
                </div>
            </div>
        `);
    }
}

// DELETE ITEM

3 个答案:

答案 0 :(得分:1)

我明白了。我不得不改变:

for(let i = 0; i < bookmarks.length; i++) {
        let name = bookmarks.name[i];
        let url = bookmarks.url[i];

为:

for(let i = 0; i < bookmarks.length; i++) {
        let name = bookmarks[i].name;
        let url = bookmarks[i].url;

这是因为我在nameurl中骑行,但是,我告诉浏览器在我的for循环开始时循环bookmarks

答案 1 :(得分:0)

您正在加载showBookmarks方法,然后尝试解析localStorage&#34;书签&#34;项目。当它试图遍历它并且undefined没有长度时,该值是未定义的。

if(!bookmarks){
        return;
    }

Here is the example working

答案 2 :(得分:0)

试试这个:

let bookmarks = localStorage.getItem("bookmarks") !== null ? JSON.parse(localStorage.getItem("bookmarks")) : [];