localStorage how to save a checkbox

后端 未结 4 1305
傲寒
傲寒 2020-12-09 12:49

I want to save a checkbox with localstorage. So that when i have checked the box and I close the browser and i re-open it, it will still be checked. right now if i click on

4条回答
  •  执笔经年
    2020-12-09 13:09

    am using this jquery code and is working with me better

    $(function() {
        var sound_t_s_data = localStorage.getItem("sound_t_s");
        if (sound_t_s_data == "yes") {
            $("#sound_t").prop('checked', true);
        }
        else if(sound_t_s_data == "no"){
            $("#sound_t").prop('checked', false);
        }
    });
    $("#sound_t").click(function() {
        if ($(this).is(":checked")) {
            localStorage.setItem("sound_t_s", "yes");
        } else {
            localStorage.setItem("sound_t_s", "no");            
        }
    });
    

    And if you want to us it in function use like this

    //Play Audio
    const s_a = new Audio("audio/s_a.mp3");
    $( "#s_r" ).click(function() {
        if ($('#sound_t').is(':checked')) {
            s_a.play()
        }
    });
    

提交回复
热议问题