【问题标题】:Save state of DIV element to LocalStorage将 DIV 元素的状态保存到 LocalStorage
【发布时间】:2015-09-04 17:45:54
【问题描述】:

我想隐藏/显示一些 div 的元素,取决于复选框。 我有复选框,状态已保存到 localStorage 但刷新后我的 DIV 元素未保存(以默认状态加载)。 jQuery(-移动)。 非常感谢您的帮助。

<fieldset data-role="controlgroup" data-type="vertical" data-mini="true">
    <legend>Some text.</legend>
    <div id="checkbox1">
        <label>
            <input type="checkbox" data-theme="a" name="ligne1" data-iconpos="right" checked="checked" />Ligne 1</label>
    </div>
    <div id="checkbox2">
        <label>
            <input type="checkbox" data-theme="a" name="ligne2" data-iconpos="right" checked="checked" />Ligne 2</label>
    </div>
    <div id="checkbox3">
        <label>
            <input type="checkbox" data-theme="a" name="ligne3" data-iconpos="right" checked="checked" />Ligne 3</label>
    </div>
    <fieldset>

$(document).ready(function () {
function getCurrentValue(checkMe) {
    return checkMe.is(':checkbox') ? checkMe.prop('checked') : checkMe.val();
}

function checkvalues() {
    var original = true;
    $(':input').each(function () {
        if (getCurrentValue($(this)) !== $(this).data('originalvalue')) {
            original = false;
        }
    });

    return original;
}

if (localStorage) {

    $(':input').each(function () {

        $(this).data('originalvalue', getCurrentValue($(this)));
    });

    $('#checkbox1').on('change', ':input', function () {
        if (checkvalues()) {
            $('#ligne1').show();
        } else {
            $('#ligne1').hide();
        }
    });

    $('#checkbox2').on('change', ':input', function () {
        if (checkvalues()) {
            $('#ligne2').show();
        } else {
            $('#ligne2').hide();
        }
    });

    $('#checkbox3').on('change', ':input', function () {
        if (checkvalues()) {
            $('#ligne3').show();
        } else {
            $('#ligne3').hide();
        }
    });

}});

实时示例是here

【问题讨论】:

  • 查看您的代码,我无法看到将状态保存到 localStorage 或从中检索到的任何地方。
  • 现在我添加了 JavaScript ;-) 但它是在示例中。
  • 不要这样做:if (localStorage)... 因为如果它不存在 - 你会得到一个错误。而是这样做:if (typeof localStorage !== 'undefined')...` 或:if (window.localStorage)...
  • 您的代码中仍然没有对localStorage的读/写...

标签: javascript jquery jquery-mobile checkbox local-storage


【解决方案1】:

您需要在代码中添加集合并从 localStorage 获取。

要设置数据,您需要这样的东西:

// First we setup the data in key/value pairs
var dataContainer = { 'check1':'checked', 'check2':'notchecked'}
// Then save it to localStorage
localStorage.setItem('storedData', JSON.stringify(dataContainer));

并从 localStorage 获取数据:

var dataRetrieved = localStorage.getItem('storedData');
console.log('Local Storage data:', JSON.parse(dataRetrieved))

更多关于localStorage的信息MDN Local Storage

【讨论】:

    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 2020-04-17
    • 2021-10-16
    • 2021-02-16
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多