如何将onclick html()文本保存到LocalStorage?

时间:2018-04-04 02:11:26

标签: jquery local-storage

我有一个按钮,当点击div时,文本会打印在另一个div上。我希望将此文本保存到本地存储。我试过这个:

$(".light.theme").click(function(){
$('.current-theme').html("Light is active");
localStorage.content = $('.current-theme').html();
$('.current-theme').html(localStorage.content);
});

但它不起作用。你能帮忙吗?

这是我的“处女”代码:

<div class="current-theme">Default is active</div>
<div class="light theme">Light</div>

$(".light.theme").click(function(){
    $(".current-theme").html("Light is active");
});

1 个答案:

答案 0 :(得分:1)

要保存到localStorage,您需要这样写。

window.localStorage.setItem('key', 'value')

所以在你的情况下你需要这样做

<div class="current-theme">Default is active</div>
<div class="light theme">Light</div>



$(document).ready(function(){
    $(".light.theme").click(function(){
        $(".current-theme").html("Light is active");
        window.localStorage.setItem('theme', "Light")
    });
    var theme = window.localStorage.getItem('theme');
    if(theme && theme != '') {
        $(".current-theme").html(theme+" is active");
    }  

})

要从本地存储中获取已保存的值,您需要执行此操作。 window.localStorage.getItem('theme')

相关问题