每次用户拖放时,我都想将一个 id 存储到 localStorage
I want to store an id to the localStorage each time when a user drag and drops
我有两个面板。在左侧面板上,我将所有具有唯一 ID 的卡片作为 id 属性提供给 div。当用户拖放到其他面板上时。我在右侧面板上使用唯一 id 来追加子对象,追加部分工作正常。现在我想将该 id 存储在本地存储中,以便我可以映射它们并将它们从我用来映射左侧面板上的所有 div 卡并在右侧面板上显示它们的状态中过滤掉,这样即使用户刷新它也能正常工作。
enter code here const onCardDrop = (e) => {
const card = e.dataTransfer.getData('card')
console.log(card) // card example 37i9dQZF1DX0u8vIGVgue9
e.stopPropagation();
e.target.appendChild(document.getElementById(card))
// After this line I want to store the card on local Storage to map the card in future
// And I want to append the each card id to the local storage to map them easily
toast();
let arr;
}
我尝试写一段很长的代码保存到本地存储中,但它正在返回字符串,一切都变得一团糟
我不确定我是否答对了你的问题。 Local Storage只能存储键值对的字符串(见Local Storage Docs)
这就是您存储和读取字符串的方式。
window.localStorage.setItem('foo', 'bar');
const str = window.localStorage('foo'); // str === 'bar'
要存储对象或数组,您需要先将其序列化为任何字符串(我更喜欢 JSON)
window.localStorage.setItem('objTest', JSON.serialize({ x: 2, y: 3 }));
const obj = JSON.parse(window.localStorage('objTest'));
window.localStorage.setItem('arrTest', JSON.serialize([1,2,3,4,5]));
const obj = JSON.parse(window.localStorage('arrTest'));
我有两个面板。在左侧面板上,我将所有具有唯一 ID 的卡片作为 id 属性提供给 div。当用户拖放到其他面板上时。我在右侧面板上使用唯一 id 来追加子对象,追加部分工作正常。现在我想将该 id 存储在本地存储中,以便我可以映射它们并将它们从我用来映射左侧面板上的所有 div 卡并在右侧面板上显示它们的状态中过滤掉,这样即使用户刷新它也能正常工作。
enter code here const onCardDrop = (e) => {
const card = e.dataTransfer.getData('card')
console.log(card) // card example 37i9dQZF1DX0u8vIGVgue9
e.stopPropagation();
e.target.appendChild(document.getElementById(card))
// After this line I want to store the card on local Storage to map the card in future
// And I want to append the each card id to the local storage to map them easily
toast();
let arr;
}
我尝试写一段很长的代码保存到本地存储中,但它正在返回字符串,一切都变得一团糟
我不确定我是否答对了你的问题。 Local Storage只能存储键值对的字符串(见Local Storage Docs)
这就是您存储和读取字符串的方式。
window.localStorage.setItem('foo', 'bar');
const str = window.localStorage('foo'); // str === 'bar'
要存储对象或数组,您需要先将其序列化为任何字符串(我更喜欢 JSON)
window.localStorage.setItem('objTest', JSON.serialize({ x: 2, y: 3 }));
const obj = JSON.parse(window.localStorage('objTest'));
window.localStorage.setItem('arrTest', JSON.serialize([1,2,3,4,5]));
const obj = JSON.parse(window.localStorage('arrTest'));