我有一個名爲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我只是認爲這是暗示。我會更新我的代碼以反映這一變化。 –
非常感謝!有效。 –