Localstorage值未在页面刷新时重置

时间:2017-08-25 07:05:27

标签: javascript local-storage

用户从选择框中选择的值设置为按钮值,但它(LocalStorage)值在页面刷新时更改(F5)



function change(){
        var opt = $("#gsb_tb option:selected").text();
        var stored =  localStorage.setItem('project',JSON.stringify(opt));
        var valueofstore= JSON.parse(localStorage.getItem('project'));
        document.getElementById("set-project").value= valueofstore;
    }

<select id="gsb_tb" style="height: 45px; width: 78%; margin-left: 70px; padding-right: 90px; vertical-align: middle;" tabindex="0" autocomplete="off">
<option value="" disabled selected>Select your Project</option>
<option value="370"> E-Card</option>
<option value="278">Labs</option>
<option value="196">Absolute DB</option>

<input value="Set as Working Project" onclick="change()" aria-label="I'm Feeling Lucky" name="btnI" class='center-btn' jsaction="sf.lck" type="submit" id='set-project'>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您的意思是当您正确刷新页面时,不会反映您对localStorage的选定和保存值?

如果这是正确的,保存到localStorage没有任何问题,但您需要恢复该值以选择&gt;期权价值。

答案 1 :(得分:1)

根据我的理解,您可能正在寻找window.onload

function change(){
    var opt = $("#gsb_tb option:selected").text();
    var stored =  localStorage.setItem('project',JSON.stringify(opt));
    var valueofstore= JSON.parse(localStorage.getItem('project'));
    console.log(valueofstore)
    document.getElementById("set-project").value= valueofstore;
}
function load(){
    var valueofstore= JSON.parse(localStorage.getItem('project'));
    console.log(valueofstore)
    if (valueofstore){
        document.getElementById("set-project").value= valueofstore;
    }
}
window.onload = load;

答案 2 :(得分:0)

这样的东西?

您需要在页面加载

上加载本地存储中的数据
<select id="gsb_tb" style="height: 45px; width: 78%; margin-left: 70px; padding-right: 90px; vertical-align: middle;" tabindex="0" autocomplete="off">
<option value="" disabled selected>Select your Project</option>
<option value="370"> E-Card</option>
<option value="278">Labs</option>
<option value="196">Absolute DB</option>
</select>

<button value="s" type="button" id='set-project'>Change</button>

JS

$(document).ready(function(){
    var project = localStorage.getItem('project');
  if(undefined !== project && project != "")
  {
    document.getElementById("set-project").innerHTML = project;
  }

    $("#set-project").on("click", update);

})

function update(){
    var opt = $("#gsb_tb option:selected").text();
    var stored =  localStorage.setItem('project',opt);
    var valueofstore= localStorage.getItem('project');
    document.getElementById("set-project").value= valueofstore;
    document.getElementById("set-project").innerHTML= valueofstore;
}

JSFiddle