【问题标题】:HTML5 localStorage: Big JSON, specific value as condition to change CSS (favorite list)HTML5 localStorage:大 JSON,特定值作为更改 CSS 的条件(收藏夹列表)
【发布时间】:2013-01-24 10:55:40
【问题描述】:

给定 localStorage 中的大型 JSON 表和给定键,如何访问关联值并将其用作 CSS 的条件?

鉴于以下 JSON:

var data = [ 
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C', 'status': 1 },
{ 'myKey': 'D', 'status': 1 }
];

以下 html 进行风格化:

<p id="A">AA</p>
<p id="B">BB</p>
<p id="C">CC</p>
<p id="D">DD</p>

以下css

.status1 { color: green; }
.status0 { color: red; }

这是“点击收藏/收藏列表/收藏明星”背后的基本原则之一。

【问题讨论】:

    标签: javascript jquery json local-storage


    【解决方案1】:

    工作示例on fiddle, JQuery

    0。应用技巧!:JSON 和本地存储

    /* To store JSON in localStorage, you compress it as string */
        localStorage["results"] = JSON.stringify(data); // or lS.restults
    
    /* Whenever you want to work on it, need to uncompress the JSON */
        var data = JSON.parse(localStorage["results"]);
    

    1.创建元函数:getJsonVal()

    //META.Fn: pullVal
    function getJsonVal(json, itemId) {
        for (var i in json) {
            if (json[i].myKey == itemId) {
                return json[i]; 
            }
        }
    }
    

    2。在相应地注入 CSS 类之前检查 JSON 值的函数

    //META.Fn: loadSwitch [check localStorage & set CSS
    function loadSwitchCSS($set, i) {
        setTimeout(function () {
            var myID = $set.eq(i).attr('id'); // a. Get key [my case: from the html ID]
            alert("look at:"+ myID);
            var val = getJsonVal(data, myID).status;
            // alert(data);
            if (val == 1) { // c. CSS remove-add: so if...else... CSS
                $set.eq(i).removeClass().addClass('status1');
            } else {
                $set.eq(i).removeClass().addClass('status0')
            }
            if (i < $set.length - 1) {
                loadSwitchCSS($set, i + 1);
            }
        }, 100);
    }
    

    3.加载时触发函数:

    loadSwitchCSS($('p'), 0);
    

    【讨论】:

      猜你喜欢
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2021-06-26
      • 1970-01-01
      • 2011-12-27
      • 2021-07-06
      • 1970-01-01
      相关资源
      最近更新 更多