我有一个名为category.html的页面。我试图在JavaScript localStorage中存储类别的值,以便我可以将它传递到下一个html页面。我试图通过localStorage中的类别变量的值传递单元格中的单击元素,但在第一次单击时不会发生这种情况。它在第一次点击后有效。我究竟做错了什么?JavaScript localStorage无法在第一次点击
<html>
<!--
https://jsfiddle.net/vu9d9mzb/#&togetherjs=sgTRTjfJ0m
-->
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
function store() {
var display = document.getElementById("result");
$("a").click(function() {
var nameOfCategory = $(this).attr("categoryName");
nameOfCategory = String(nameOfCategory);
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("category", nameOfCategory);
// Retrieve
var checkLocalStorage = localStorage.getItem("category");
display.innerHTML = "Value of checkLocalStorage variable: " + checkLocalStorage + "<br>";
//console.log("Value of checkLocalStorage variable: " + checkLocalStorage);
} else {
displayMessage.innerHTML = "Sorry, your browser does not support Web Storage..." + "<br>";
//console.log("Sorry, your browser does not support Web Storage...");
}
display.innerHTML += "Value of nameOfCategory varaible: " + nameOfCategory + "<br>";
//console.log("Value of nameOfCategory varaible: " + nameOfCategory);
}); // end of a.click function
}
</script>
</head>
<body>
<table>
<tr>
<th>Category</th>
</tr>
<tr>
<td><a onclick=store() categoryName="Fruits">Fruits</a>
</td>
</tr>
<tr>
<td><a onclick=store() categoryName="Vegetables">Vegetables</a>
</td>
</tr>
<tr>
<td><a onclick=store() categoryName="Clothes">Clothes</a>
</td>
</tr>
</table>
<div id="result">
</div>
</body>
</html>
如果代码不跑这里来了,由于跨来源问题,那么这里就是的jsfiddle链接到它: - https://jsfiddle.net/vu9d9mzb/#&togetherjs=sgTRTjfJ0m
正确,@JonathanLonowski我只是认为这是暗示。我会更新我的代码以反映这一变化。 –
非常感谢!有效。 –