javascript - localStorage is null, but only from one function and not another
问题描述
I have a PHP page that loads two JS files at the end. In the first file I have this...
// global variables
var refineSearchStorage = {};
// function calls
window.addEventListener("load", function() {
refineSearchStorage.get();
});
refineSearchStorage = {
data : null, // empty storage
get : function() {
refineSearchStorage.data = localStorage.getItem("refineSearchStorage");
if(refineSearchStorage.data === null) {
refineSearchStorage.data = { refineKeywords: '' };
refineSearchStorage.save();
}
else {
refineSearchStorage.data = JSON.parse(refineSearchStorage.data);
}
},
add : function(x) {
refineSearchStorage.data.refineKeywords = x;
refineSearchStorage.save();
},
save : function() {
localStorage.setItem("refineSearchStorage", JSON.stringify(refineSearchStorage.data));
}
};
Inline javascript calls Function 1 from the middle of the page. It is created by PHP after a search result...
<script>
window.addEventListener('load', function () {
searchActions('{$keywords_human}');
});
</script>
Function 1 appears in the 2nd JS page and the result is Uncaught TypeError: Cannot set property 'refineKeywords' of null
... instead of adding to the localStorage.
function searchActions(x) {
refineSearchStorage.add(x);
}
Function 2 below is called with the click of a button and adds to a localStorage variable without issue. It is also located on the 2nd JS page...
function keywordAdd(y) {
var existingParams = refineSearchStorage.data.refineKeywords;
var param = y.toLowerCase();
var newParams;
newParams = (existingParams + ' ' + param).trim();
refineSearchStorage.add(newParams);
}
Function 1 used to work, but I did something to break it when I split the functions on to different pages. What did I do?
解决方案
这是因为
window.addEventListener('load', function () {
searchActions('{$keywords_human}');
});
之前被调用
window.addEventListener("load", function() {
refineSearchStorage.get();
});
推荐阅读
- mysql - SQL 语句只取 id 小于 6 位的 MYSQL
- python - Twilio SMS 响应 - Python 快速入门指南 - 404 Not Found
- android - 导航上的片段生命周期重叠
- excel - 具有多个数据集的 Excel 回归
- java - Jax RS 构建来自枚举的响应
- database - 从 MongoDB Atlas 迁移我的数据
- hyperledger - 使用 composer-rest-server 访问 OAuth 范围信息
- python - 运行 keras-text-summarization 时没有名为“keras_text_summarization”的模块
- c++ - 为什么允许这种 C++ 类型推导
- php - 在 php 5.6.23 中设置变量值