我有一个运行良好的脚本,用于检查访问者是否已分配优惠券代码,但我想添加功能来检索分配给他们的优惠券代码并显示它。两者都依赖于 localStorage 属性。我遇到的问题是,当我显示存储值时,它返回 [object HTMLSpanElement]
而不是应该分配的值。
我在这个问题上发现的几乎所有内容都是由于范围引起的,但我不明白我是如何遇到范围问题的……甚至尝试使变量在范围内成为全局变量,但似乎没有做任何事情.
这是JS:
if(localStorage.getItem("visited") != "true"){
localStorage.setItem("visited","true");
var codeValue = document.getElementById("code");
localStorage.setItem("code",codeValue);
}
else {
var savedCode = localStorage.getItem("code");
document.getElementById("message").innerHTML = "You've already been assigned coupon code " + savedCode;
}
这是相关的 HTML:
<span id="message">Your coupon code is: <span id="code">CODE1234</span></span>
当您访问该页面后返回该页面时,我希望跨度文本显示 You've already been assigned coupon code CODE1234
,而是返回 You've already been assigned coupon code [object HTMLSpanElement]
请注意,部分脚本是我之前创建并投入生产的,我基本上是在利用该功能。以前,如果 getItem("visited") != "true"
返回 false,它会弹出一个警告框并说你已经得到了一个代码,然后将你重定向到另一个页面。
最佳答案
您正在将元素本身(它是一个对象)存储在 localStorage 中。您应该存储元素的文本。
改变
var codeValue = document.getElementById("code");
到
var codeValue = document.getElementById("code").textContent;
请注意:根据Window.localStorage
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
关于javascript - 为什么我的 localStorage.getItem 变量返回 "object HTMLSpanElement"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55614424/