保存到本地存储



我想用html保存数据或值,并在页面再次调用时再次使用它们。我这里有一个来自https://www.w3schools.com/html/html5_webstorage.asp的例子,它是如何在html中工作的,整个事情也在blazor中工作吗?

function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>

实际上Blazor只能通过JavaScript访问浏览器本地存储- WASM不能直接访问。

然而,如果你使用像https://github.com/Blazored/LocalStorage这样的库,这就容易多了——它将提供必要的JS,并且可以作为服务注入。

最新更新