即使重新加载javascript后,我如何保留值的价值

时间:2016-02-16 04:50:28

标签: javascript jquery

这是我的脚本。文件准备就绪后我就座了

$(document).ready(function(){           
    localStorage.searchFlag = false;
    localStorage.search = "";
    alert(localStorage.searchFlag + " search:" + localStorage.search);
});

当我点击提交按钮时,我想更改searchFlag的值并搜索

<form class="form-search" style="float:right" action="javascript:searchKeyword('search-inbox');" method="POST" id="search-inbox">
  <input type="text" class="input-large search-query" style="height:30px">
  <button type="submit" class="btn search" id="search-inbox">Search</button>
</form>

function searchKeyword(search){      
     var keyword = $(".search-query").val();
     var offset = start - 1;
     localStorage.searchFlag = true;
     localStorage.search = search;
     search = search;        
    $.ajax({
        type: "POST",
        url: "<?php echo site_url("network_test/searchmessages"); ?>",
        data: {keyword: keyword, search: search, offset: offset},
        dataType: "json",
        success: function(data){
    if(search == "search-inbox"){
                $("#message-body").html(data.html);
            } else if(search == "search-sent"){
                $("#message-list").html(data.html);
            }
        }
    });
    alert(localStorage.searchFlag + " search:" + localStorage.search);
}

请帮助我成为网络开发的新手

2 个答案:

答案 0 :(得分:0)

您从本地存储中存储和获取值的方式不正确。

$(document).ready(function(){   
    sessionStorage.setItem('searchFlag ','false');  
    sessionStorage.setItem('search','');
    alert(sessionStorage.getItem('search') + " search:" + sessionStorage.getItem('searchFlag '));
});

sessionStorage属性允许您访问会话存储对象。 sessionStorage类似于Window.localStorage,唯一的区别是当localStorage中存储的数据没有到期设置时,存储在sessionStorage中的数据在页面会话结束时被清除。只要浏览器处于打开状态,页面会话就会持续,并且会在页面重新加载和恢复后继续存在。在新选项卡或窗口中打开页面将导致启动新会话,这与会话cookie的工作方式不同。

FIDDLE DEMO 1

$(document).ready(function(){   
    localStorage.setItem('searchFlag ','false');  
    localStorage.setItem('search','');
    alert(localStorage.getItem('search') + " search:" + localStorage.getItem('searchFlag '));
});

FIDDLE DEMO 2

答案 1 :(得分:0)

而不是这样:

localStorage.searchFlag = false;

您需要像这样设置:

localStorage.setItem('searchFlag','false');

让他们像这样使用:

localStorage.getItem('searchFlag');

这是一个很好的tutorial