如果它的id作为本地存储对象的键存在,如何更改按钮类

时间:2014-02-04 20:25:14

标签: javascript jquery json local-storage

我正在尝试更改按钮的类,如果它的id出现在我当前正在使用以下的本地存储对象中。本地存储对象存储为json对象;

{"latlng":"(50.000000, -50.00000)","address":"1235 any street","image":"http://localhost/images/image.jpg","id":123456789}


window.addEventListener("load", changeButton, false);

function changeButton() {
    for(var i = 0; i < localStorage.length; ++i) {
        key = localStorage.key(i);
        json = JSON.parse(localStorage.getItem(localStorage.key(i)));
        if(key == json.id) {
            $("#" + json.id).removeClass('btn-custom').addClass('btn-success').empty().html('<i class="fa fa-check"></i> Added').button('refresh'); 
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果我没有错,你正在谈论如果它的id存在于localStorage字符串化对象中,则更改按钮的类名。

如果是这样,首先你必须从localStorage解析stringified对象,然后你必须运行for in循环来检查是否匹配了button和object的id。

这是代码

<!DOCTYPE html>
<html>
<head></head>

<body >
<button id="myName"> my value</button>
</body>

<script>
var obj = {name:'suman', id:'myName', address :'lodhi road'};
localStorage.myobj = JSON.stringify(obj);
var buttonId = "myName";
function changeButton() {
    var myObj = JSON.parse(localStorage.myobj);
    for(var i in myObj){
        //buttonId is defined above, its depend on you, how you would get on here
        if(myObj[i] == buttonId){
            //alert('success');
            $("#" + json.id).removeClass('btn-custom').addClass('btn-success').empty().html('<i class="fa fa-check"></i> Added').button('refresh'); 
        }
    }
}

window.addEventListener("load", changeButton, false);

</script>
</html>