localStorage不知何故混淆了我所有的数字



我正在创建一个扩展,它是浏览器上的一个粘性按钮,当点击它时,它会加载您保存的下一篇文章。这些文章存储在firebase数据库中,并在页面加载时获取。

我添加了一个指针变量来索引数组,并将指针的值存储在本地存储中,以便在页面刷新时使用它。我能够正确地减去指针的值,当我试图在点击时加载下一个URL时,由于某种原因,它会加载一个完全不同的URL。

获取数据的形状:

data = [
{
book: "the matrix,
url: 'https://thisurl1.com
},
{
book: "the matrix 2,
url: 'https://thisurl2.com
},
{
book: "the matrix 3,
url: 'https://thisurl3.com
}
]

代码如下:

// check if local storage is available
const storageAvailable = (type) => {
}
// fetches articles from article endpoint => [data]
const fetchArticles = async () => {
try {
const response = await fetch("url_endpoint");
const data = await response.json();
articleStorage = Object.values(data);
localStorage.setItem("articles", JSON.stringify(articleStorage))
const pointer = Number(localStorage.getItem("pointer"));
if (pointer === null || pointer < 0 || pointer > articleStorage.length - 1) {
localStorage.setItem("pointer", articleStorage.length - 1);
}
return;
} catch (err) {
console.log(err);
}
};
// create the next button
const nextButton = () => {
// creating tags and buttons
// styling the button
// loads next article on click
button.addEventListener("click", loadNextArticle);
// appending to dom
};
// loads next article in array
const loadNextArticle = () => {
const pointer = Number(localStorage.getItem("pointer"));
const newPointer = pointer - 1;
const articleStorage = JSON.parse(localStorage.getItem('articles'));
if (pointer < 0 || pointer > articleStorage.length - 1) {
alert('nothing else to show');
} else {
localStorage.setItem('pointer', newPointer);
window.location.href = articleStorage[newPointer].link;
}
};
window.onload = () => {
if (storageAvailable('localStorage')) {
if (localStorage.getItem("articles") === null) fetchArticles();
nextButton();
} else {
console.log('local storage not available');
}
};

你从不更新指针

console.log(pointer); // <-- read pointer
localStorage.setItem("pointer", pointer - 1); // <-- update local storage
if (pointer < 0 || pointer > articleStorage.length - 1) { // <-- still the same pointer value

你需要更新变量,因为它不会自己更新

pointer--; // update the variable
localStorage.setItem("pointer", pointer); 
if (pointer < 0 || pointer > articleStorage.length - 1) { 

最新更新