在VS Code里面预览可以显示如图:
在浏览器预览就不能显示了,刚开始还好的后来不知道弄错了哪里了,哭死
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body {
background-color: #144756;
}
#my-div {
border: 2px dashed #ccc;
width: 320px;
text-align: center;
}
#list {
table {
text-align: center;
background-color: aqua;
}
}
</style>
<body>
<div id="my-div">
<form action="#">
<input type="text" id="user-account" placeholder="请输入账号" />
<input type="password" id="user-password" placeholder="请输入密码" />
<input type="text" id="user-explanation" placeholder="请输入说明" />
<input type="button" onclick="save()" value="新增记录" />
</form>
<hr />
<input type="text" id="search_site" name="search_site" placeholder="输入别名(key)查看密码" />
<input type="button" onclick="find()" value="查找网站" />
<p id="find_result"><br /></p>
<button id="delete">对选择进行删除</button>
</div>
<br />
<div id="list">
</div>
<script>
userAll();
//保存数据
function save() {
var user = new Object;
user.account = document.getElementById("user-account").value;
user.password = document.getElementById("user-password").value;
user.explanation = document.getElementById("user-explanation").value;
var str = JSON.stringify(user); // 将对象转换为字符串
localStorage.setItem(user.account, str);
alert("保存成功");
userAll();
}
//查找数据
function find() {
var search_site = document.getElementById("search_site").value;
var str = localStorage.getItem(search_site);
var find_result = document.getElementById("find_result");
var user = JSON.parse(str);
find_result.innerHTML = search_site + "密码为:" + user.password;
}
function userAll() {
var list = document.getElementById("list");
if (localStorage.length > 0) {
var result = "<table border='1'>";
result += "<tr><th>序号</th><td>账号</td><td>密码</td><td>说明</td><th>操作</th></tr>";
for (var i = 0; i < localStorage.length; i++) {
var account = localStorage.key(i);
var str = localStorage.getItem(account);
var user = JSON.parse(str);
result += "<tr>" +
"<td>" + '<button>' + (i + 1) + '</button>' + "</td>" +
"<td>" + user.account + "</td>" +
"<td>" + user.password + "</td>" +
"<td>" + user.explanation + "</td>" +
"<td>" + " <input type='checkbox' name='checkbox'>" +
"</td>" + "</tr>";
}
result += "</table>";
list.innerHTML = result;
} else {
list.innerHTML = "数据为空...";
}
// 重新绑定删除按钮事件
var deleteBtn = document.getElementById("delete");
deleteBtn.onclick = function () {
if (confirm("是否删除所选?")) {
var checkboxes = document.getElementsByName("checkbox");
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
// 从localStorage中删除对应的数据
var sitename = checkboxes[i].parentNode.previousElementSibling.previousElementSibling.textContent;
localStorage.removeItem(sitename);
// 删除选中的行
checkboxes[i].parentNode.parentNode.parentNode.removeChild(checkboxes[i].parentNode.parentNode);
i--; // 注意:删除后需递减i,否则会漏掉后续的项目
}
}
userAll();
}
}
};
</script>
</body>
</html>