简体   繁体   English

将值从Span ID保存到本地存储HTML5

[英]Save value from Span ID to local Storage HTML5

created a jsfiddle where im trying to get the value (800) thats created by the up and down buttons to save locally 创建了一个jsfiddle,我在其中尝试获取由向上和向下按钮创建的值(800),以将其保存在本地

however the example keeps saving out the key and value in the text box 但是该示例一直在文本框中保存键和值

http://jsfiddle.net/HMEVd/143/ http://jsfiddle.net/HMEVd/143/

var prefix = "";
$("#power_save").click(function () { 
var key = $("#key").attr('value');
var value = $("#value").attr('value');
var power_save = $("#CountedClicks").attr('value');
localStorage.setItem(prefix + key, value, power);      //******* setItem()
//localStorage[prefix+key] = value; also works
RewriteFromStorage();
});

function RewriteFromStorage() {
$("#data").empty();
for(var i = 0; i < localStorage.length; i++)    //******* length
{
    var key = localStorage.key(i);              //******* key()
    if(key.indexOf(prefix) == 0) {
        var CountedClicks = localStorage.getItem(key);  //******* getItem()
        //var value = localStorage[key]; also works
        var shortkey = key.replace(prefix, "");
        $("#data").append(
            $("<div class='kvp'>").html(shortkey + "=" + value)
               .append($("<input type='button' value='Delete'>")
                       .attr('key', key)
                       .click(function() {      //****** removeItem()
                            localStorage.removeItem($(this).attr('key'));
                            RewriteFromStorage();
                        })
                      )
        );
    }
}
}

RewriteFromStorage();

How can i get it so that: 我如何获得它以便:

1.The KEY is predefined such as POWER? 1. KEY是预定义的,例如POWER? 2. VALUE saved out is the countedclicks ie the number that changes with the up and down button? 2.保存的VALUE是计数的点击数,即随着上下按钮变化的数字吗?

You are using setItem() incorrectly, it takes one key and one value: 您使用的setItem()错误,它需要一个键和一个值:

  [NameSetter] void setItem(in DOMString key, in DOMString data);

ref: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage 参考: https : //developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

If you want to use the same key to access both values, you could simply put them in an array: 如果要使用相同的键来访问两个值,则可以将它们简单地放入数组中:

  localStorage.setItem(prefix + key, [value, power]);   

Then you would access them via: 然后,您可以通过以下方式访问它们:

  value = localStorage.getItem(prefix + key)[0];
  power = localStorage.getItem(prefix + key)[1];

Alternatively you could simply use two different keys for two separate entries. 或者,您可以简单地将两个不同的键用于两个单独的条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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