Javascript 未定义本地存储:JQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30641571/
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
local Storage is not defined : JQuery
提问by Chamalee De Silva
I am using this piece of code inside a javascript function. But when I run the application it gives a reference error that local Storage is not defined.
我在 javascript 函数中使用这段代码。但是当我运行该应用程序时,它给出了一个未定义本地存储的引用错误。
localStorage.setItem(result.key+authAppParams.application , result.key);
Why this occurs? Why can't I use this inside a function? Since it is a setItem and all the releated values are inside the method I cannot define the local Storage globally.
为什么会出现这种情况?为什么我不能在函数中使用它?由于它是一个 setItem 并且所有相关值都在方法内,因此我无法全局定义本地存储。
How can I avoid this issue and make this work?
我怎样才能避免这个问题并使这个工作?
回答by vernak2539
When using localStorage you should always check for it first to make sure the browser has it implemented.
使用 localStorage 时,您应该始终首先检查它以确保浏览器已实现它。
Something like this
像这样的东西
if(window.localStorage) {
// localStorage can be used
} else {
// can't be used
}
Should probably check for it early on in your code and only use it if it's available.
可能应该在代码中尽早检查它,并且仅在可用时才使用它。
JS will always look on the global for a variable that it cannot find in the current context, so it looks as if it comes down to the browser not having it.
JS 将始终在全局上查找在当前上下文中找不到的变量,因此看起来好像归结为浏览器没有它。
EditLike everyone is commenting, localStorage and jQuery are completely separate
编辑就像大家评论的一样,localStorage 和 jQuery 是完全分开的

