本地存储迭代获取for循环中单击按钮的值

时间:2014-12-10 10:01:46

标签: javascript jquery json

我有这段代码:

for(var i = 0; i < localStorage.length; i++){
                var dataNya = JSON.parse(localStorage.key(i));
                // console.log(dataNya);
                var displayUlit = "";
                    displayUlit += "<br/>";
                var spaceTo = "";
                    spaceTo += " || ";
                console.log(dataNya);
                    var keme = localStorage.getItem(localStorage.key(i));
                $("#pangDisplay").append(dataNya + spaceTo + "<button class='pangEdit' value="+dataNya+">"+JSON.parse(keme)+"</button>" + "  " + displayUlit);
                console.log(JSON.parse(keme));
                // localStorage.setItem(JSON.stringify(dataNya), JSON.stringify("complete"));
            }
            $(".pangEdit").click(function(e){
                e.preventDefault();

                var pangInput = $(".pangEdit").val();
                console.log(pangInput);
                localStorage.setItem(JSON.stringify(pangInput), JSON.stringify("complete"));
            });

我想获取localstorage的密钥,我可以在其中传递数据并更新其值。帮帮我谢谢

1 个答案:

答案 0 :(得分:1)

您可以在jQuery中使用附加的data属性:

for (var i = 0; i < localStorage.length; i++) {
    var dataNya = localStorage.key(i);

    var displayUlit = "";
    displayUlit += "<br/>";

    var spaceTo = "";
    spaceTo += " || ";

    var keme = localStorage.getItem(dataNya);
    var button = "<button class='pangEdit' data-storagekey='" + dataNya + "' value='" + dataNya + "'>" + keme + "</button>";
    $("#pangDisplay").append(dataNya + spaceTo + button + "  " + displayUlit);
}

$(".pangEdit").click(function(e) {
    e.preventDefault();

    var dataNya = $(this).data('storagekey');

    localStorage.setItem(dataNya, "complete");
});