这是我试过的方法。我添加了一个反馈,仅用于测试JavaScript变量siteName是否包含HTML文本框值的值,但它反映了“[object HTMLInputElement]”。知道为什么吗?
<!DOCTYPE html>
<html>
<head>
<title>Storing HTML value into Javascript local storage</title>
</head>
<body>
<h1 id="2ndid">Hello</h1>
<input type="text" id="firstid">
<button onclick="myFunction()">LocalStorage</button>
<button onclick="myFunction2()">Feedback</button>
<script type="text/javascript">
var siteName = document.getElementById('firstid');
function myFunction() {
localStorage.setItem('store1', siteName);
}
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName;
}
</script>
</body>
</html>
您必须使用value
属性从输入中获取实际文本。否则它将返回输入文本字段的引用。引用是HTMLInputElement
的类型,它具有value
属性,保存在文本字段中输入的实际数据。
<!DOCTYPE html>
<html>
<head>
<title>Storing HTML value into Javascript local storage</title>
</head>
<body>
<h1 id="2ndid">Hello</h1>
<input type="text" id="firstid">
<button onclick="myFunction()">LocalStorage</button>
<button onclick="myFunction2()">Feedback</button>
<script type="text/javascript">
var siteName;
function myFunction() {
siteName = document.getElementById('firstid').value;
localStorage.setItem('store1', siteName);
}
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName;
}
</script>
</body>
</html>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
使用input元素的value
从值表单中检索它,否则你将获得一个对象。
document.getElementById("2ndid").innerHTML = siteName.value;
这是一个非常简单的修复,你只需要在第二个函数结束时添加value属性。
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName.value;
}
您没有初始化您的变量。
这是一个有效的代码。
<!DOCTYPE html>
<html>
<head>
<title>Storing HTML value into Javascript local storage</title>
</head>
<body>
<h1 id="2ndid">Hello</h1>
<input type="text" id="firstid">
<button onclick="myFunction()">LocalStorage</button>
<button onclick="myFunction2()">Feedback</button>
<script type="text/javascript">
var siteName;
function myFunction() {
siteName= document.getElementById('firstid').value;
localStorage.setItem('store1', siteName);
}
function myFunction2() {
document.getElementById("2ndid").innerHTML = siteName;
}
</script>
</body>
</html>