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

问题描述 投票:0回答:1

我有一个按钮,当单击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");
});
jquery local-storage
1个回答
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')

© www.soinside.com 2019 - 2024. All rights reserved.