简体   繁体   中英

localStorage (Need help doesn't function properly) - Javascript Chrome Extension

var itemName;
var itemSize;
var itemType;
var itemColor;

window.onload = function() {
    document.getElementById('item_save').onclick = function() {

        var item_name = document.getElementById('item_name').value;
        var item_size = document.getElementById('item_size').value;
        var item_type = document.getElementById('item_type').value;
        var item_color = document.getElementById('item_color').value;

        console.log(item_name + "\t" + item_size + "\t" + item_type + "\t" + item_color + "\tsaving...");

        localStorage.setItem(itemName, item_name);
        localStorage.setItem(itemSize, item_size);
        localStorage.setItem(itemType, item_type);
        localStorage.setItem(itemColor, item_color);


    }

    var getItemName = localStorage.getItem(itemName);
    var getItemSize = localStorage.getItem(itemSize);
    var getItemType = localStorage.getItem(itemType);
    var getItemColor = localStorage.getItem(itemColor);

    console.log(getItemName + "\t" + getItemSize + "\t" + getItemType + "\t" + getItemColor + "\tsaved...")
}

Say if I enter 1 for the item_name input, 2 for the item_size input, 3 for the item_type input and 4 for the item_color input, it keeps displaying in console as:

"4 4 4 4 saved...

1 2 3 4 saving..."

I was wondering why it displays the saved console.log first as well and making all the numbers 4 in the saved console.log, need advice.

The "saving" console appears on event "click".

The "saved" console appears on event "load".

Of course, the loading is done before any other event is fired, liked "click".

And just like said @Pointy, the first parameter of "saveItem" and "getItem" should be a string.

By this way, you saved everything under "undefined" key and got everything under "undefined" key. Then, you only got the last saved value 4 and fourth times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM