简体   繁体   English

从另一个javascript文件中获取localStorage变量的值

[英]Getting the value of a variable from localStorage from a different javascript file

having a problem using localstorage in javascript. 在javascript中使用localstorage时遇到问题。 I have two javascript files and one multi-page html file. 我有两个javascript文件和一个多页html文件。 I'm setting the value of a variable to store in local storage in the home.js class and I then want to get the value of the same variable in my editCase.js class. 我将变量的值设置为存储在home.js类的本地存储中,然后我想在editCase.js类中获取相同变量的值。 Is this possible? 这可能吗? The goal here is to use the variable several places in the html file. 这里的目标是在html文件中使用变量的几个位置。

home.js: home.js:

var _NSCaseId;
var nsId;
$("#listOfCases li").click(function(){
            nsId = $(this).attr('id');
            LocalStorage.save(_NSCaseId, nsId);
            alert(nsId);
        });

As you can see, the value is the id of a listview item. 如您所见,该值是listview项的id。 This works fine and the alert shows the correct value every time. 此工作正常,警报每次都显示正确的值。

I then want to use the same variable in the editCase.js file: 然后我想在editCase.js文件中使用相同的变量:

var id = LocalStorage.get(_NSCaseId);
    alert(id);

But I get an error in logcat saying _NSCaseId is undefined in editCase.js 但我在logcat中收到错误,说在editCase.js中未定义_NSCaseId

Any suggestions? 有什么建议?

This shouldn't be working at all. 这应该根本不起作用。 Its localStorage (JS is very case sensitive), and to save an item, you use setItem , change your syntax to: 它的localStorage (JS非常区分大小写),为了保存项目,你使用setItem ,将你的语法更改为:

//You would not define var _NSCaseId and save the var, you save a string key
localStorage.setItem('_NSCaseId', nsId); //set

And to get 得到

localStorage.getItem('_NSCaseId');

See DOM Storage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage 请参阅DOM存储: https//developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM