javascript - 当网页保存在我的 PC 上而不是在线时,如何保存网页的状态?
问题描述
我的网页保存在我的电脑上,而不是在线。我有 .html 文件和 .txt 文件来编辑它们。localStorage 和 sessionStorage 不起作用。我还没有尝试过饼干,但我假设它们也不起作用。我需要知道如何将我的页面状态保存到指定路径,或者我需要知道如何将我的页面放在服务器上以便 localStorage 能够正常工作。
我正在尝试编写视频游戏。我熟悉电子游戏的大部分方面,保存应该比这更简单。我只熟悉 html 和 JavaScript。这是一些应该使 localStorage 工作的代码示例(只要带有代码的页面在线,它就可以正常工作)。
我已尝试过 localStorage 和 sessionStorage,但我的页面不在线,它们保存在我的 PC 上。
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
sessionStorage.setItem("lastname", "Smith");
// Store
sessionStorage.setItem("firstname","John ");
// Retrieve
document.getElementById("result").innerHTML =
sessionStorage.getItem("firstname")+
sessionStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does
not support Web Storage...";
}
</script>
</body>
该代码的结果应该是“John Smith”(不带引号)。实际结果,没有。就像我说的,我的页面存储在我的电脑上,我不知道如何将页面加载到网络上,我在那里有点菜鸟。我知道代码有效,因为我从 w3schools 获得了该代码,并且在那里运行良好。有没有办法在不上传页面的情况下保存我的页面状态?如果没有,我如何将我的页面上传到服务器?
解决方案
复制以下代码并将其保存mySite.html
在计算机上的某个位置。然后双击该文件以在浏览器中打开。或者将文件拖放到浏览器中。那应该行得通。不需要其他任何东西。要更改它,只需使用文本编辑器并保存即可。刷新浏览器以查看更改。
更新的代码包括一个localStorage
示例。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>John Thompson Site #1</title>
</head>
<body>
<div id="error"></div>
<div id="sessionStorage">sessionStorage</div>
<div id="localStorage">localStorage</div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
sessionStorage.setItem("lastname", "Smith");
// Store
sessionStorage.setItem("firstname","John ");
// Retrieve and write to HTML
document.getElementById("sessionStorage").innerHTML =
sessionStorage.getItem("firstname")+
sessionStorage.getItem("lastname");
// added localstorage example here
// store
localStorage.setItem('myCat', 'Tom');
// Retrieve and write to HTML
document.getElementById("localStorage").innerHTML = localStorage.getItem('myCat');
} else {
document.getElementById("error").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
推荐阅读
- php - 找不到类“Spatie\YamlFrontMatter\YamlFrontMatter”
- php - Google Drive 访问令牌自动化
- html - Angular 在取决于垫选择的输入中显示不同的占位符
- javascript - 在Javascript中过滤两个日期之间的数据
- http - Apache camel 3.6 如何从目标 HTTP 端点 URL 中删除骆驼 http 参数
- delphi - ADOConnection ADOQuery CommandTimeout,覆盖顺序(如果有的话)
- javascript - 如何在 localStorage 中正确存储新数据对象并使用 NextJS 保留旧数据?
- c++ - 在 OpenCV 上捕获实时摄像头时是否可以使用外部应用程序(或至少其设置)?
- python - APIRequestFactory 是否可以创建具有数据和用户属性的请求
- java - 我需要在 JDA 中使用什么方法来检查消息是否包含图像?