jQuery 从不同的javascript文件从localStorage获取变量的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19861265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:43:44  来源:igfitidea点击:

Getting the value of a variable from localStorage from a different javascript file

javascriptjqueryhtmllocal-storage

提问by MrJR

having a problem using localstorage in javascript. I have two javascript files and one multi-page html file. 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. Is this possible? The goal here is to use the variable several places in the html file.

在 javascript 中使用 localstorage 时遇到问题。我有两个 javascript 文件和一个多页 html 文件。我正在设置一个变量的值以存储在 home.js 类的本地存储中,然后我想在我的 editCase.js 类中获取相同变量的值。这可能吗?此处的目标是在 html 文件中的多个位置使用该变量。

home.js:

主页.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. This works fine and the alert shows the correct value every time.

如您所见,该值是列表视图项的 id。这工作正常,警报每次都显示正确的值。

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 中收到一个错误,说 _NSCaseId 在 editCase.js 中未定义

Any suggestions?

有什么建议?

回答by tymeJV

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