gpt4 book ai didi

javascript - 本地存储的困境

转载 作者:行者123 更新时间:2023-12-01 00:04:04 26 4
gpt4 key购买 nike

我正在尝试打印页面上文本框中的值。

单击按钮后,值会显示在页面上,但只显示一瞬间。

如何才能使这些值保留在页面上?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>

<h2>Local Storage - JavaScript <h2>

<fieldset>
<legend>Insert Data</legend>
<input id="inpKey" type="text" placeholder="Enter key...">
<input id="inpValue" type="text" placeholder="Enter Value...">
<button type="button" id="btnInsert">Insert Data</button>
</fieldset>

<fieldset>
<legend>Local Storage</legend>
<div id="lsOutPut"></div>
</fieldset>


<script src="action.js">

const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutPut = document.getElementById("lsOutPut");

btnInsert.onclick = function(){
const key = inpKey.value;
const value = inpValue.value;

if(key && value) {
localStorage.setItem(key, value);
location.reload();
}

for(let i = 0; i < localStorage.length; i++){
const keyx = localStorage.key(i);
const value = localStorage.getItem(keyx);

lsOutPut.innerHTML += `${keyx}: ${value}</br> `
}
}

</script>
</body>
</html>

最佳答案

在您的代码中,您有 location.reload(),这就是它重新加载页面的原因,不确定为什么您在那里,但其原因是:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>

<h2>Local Storage - JavaScript <h2>

<fieldset>
<legend>Insert Data</legend>
<input id="inpKey" type="text" placeholder="Enter key...">
<input id="inpValue" type="text" placeholder="Enter Value...">
<input type="button" id="btnInsert" value="Insert Data"/>
</fieldset>

<fieldset>
<legend>Local Storage</legend>
<div id="lsOutPut"></div>
</fieldset>


<script>

const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutPut = document.getElementById("lsOutPut");

btnInsert.onclick = function(){
const key = inpKey.value;
const value = inpValue.value;

if(key && value) {
localStorage.setItem(key, value);
}

for(let i = 0; i < localStorage.length; i++){
const keyx = localStorage.key(i);
const value = localStorage.getItem(keyx);

lsOutPut.innerHTML += `${keyx}: ${value}</br> `
}
}

</script>
</body>
</html>

关于javascript - 本地存储的困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60506820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com