【发布时间】:2021-06-28 05:10:45
【问题描述】:
我创建了一个递增和递减程序,但我想将数据从第一个浏览器传递到第二个浏览器(一个选项卡到另一个选项卡)。
在 Index.html 中有两个按钮用于递增和递减操作。在第二页上只有数据会显示,但我的代码只在同一个选项卡上工作。以及页面刷新后如何存储数据?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="/index.js"></script>
<link href="/index.css" rel="stylesheet" type="text/css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Users in Mall</title>
</head>
<body>
<div class="container">
<h1>Live Users in Mall</h1>
<div class = "card">
<button onclick = "decrement()">-</button>
<h2 id = "root">0</h2>
<button onclick = "increment()">+</button>
</div>
</div>
</body>
</html>
index.css
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background-color: rgb(255, 255, 255);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
text-align: center;
}
.card{
display: flex;
justify-content: center;
align-items: center;
height: 100%;
padding: 100px;
}
h2{
margin: 0 50px;
font-size: 50px;
}
button{
background-color: #ff9100;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
border-radius: 25px;
}
button:hover{
background-color: rgb(206, 206, 206);
color: #ff9100;
border-color: #000 ;
}
index.js
var data = 0;
document.getElementById("root").innerText = data;
function decrement() {
data = data-1;
if (data <= 0)
{
data = 0;
}
document.getElementById("root").innerText = data;
localStorage.setItem("key", data);
}
function increment() {
data = data + 1;
document.getElementById("root").innerText = data;
localStorage.setItem("key", data);
}
第二页名称为 Showdata
Showdata.html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="/index.css" rel="stylesheet" type="text/css">
<script src="/showdata.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show Live Data</title>
</head>
<body>
<h3>Users Present in Mall</h3>
<h2 id="root">0
</h2>
</body>
</html>
showdata.js
var data = localStorage.getItem("key");
document.write(data);
//output.innerHTML = data;
//document.getElementById("root").innerText=data;
谁能为我的问题提供解决方案?
【问题讨论】:
-
我对此知之甚少,无法写出完整的答案,但客户端存储是否是您正在寻找的?基本上使用两个选项卡都可以访问的客户端浏览器创建数据库?这是tutorial from Mozilla。
-
broadcastChannel 似乎合适
-
可能是SOCKET.IO
标签: javascript php html css web