我正在尝试打印页面上文本框中的值。
单击该按钮后,这些值将出现在页面上,但只会出现一秒。
我能做些什么使这些值保持在页面上?
<!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>发布于 2020-03-03 12:13:53
在您的代码中,您有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>发布于 2020-03-03 12:18:01
在您的代码中,您有location.reload(),我假设使用以前的值清除div。这将重新加载页面并导致第二个问题。在打印新值之前,将其切换到以下位置以清除该框。
if(key && value) {
localStorage.setItem(key, value);
lsOutPut.innerHTML = '';
}虽然不相关,但也值得注意的是,您没有关闭<h2>标记。
<h2>Local Storage - JavaScript</h2>https://stackoverflow.com/questions/60506820
复制相似问题