由于某些原因,在提交表单后,刷新页面所花费的时间只是值“ image-path.jpg”出现在我的页面上。如何在页面上保留“ image-path.jpg”值?我正在尝试使用localStorage来实现这一点,但该值一直在消失。
function myFunction() {
localStorage.setItem("path","image-path.jpg");
//get value of from local storage
var results = localStorage.getItem("path")
document.getElementById("result").innerHTML = results;
}
假设您的html看起来像这样:
<form id="myForm">
<label for="control"> Insert some value: </label>
<input type="text" id="control" name="control"/><br><br>
<input type="submit" value="Submit"><br><br>
</form>
<div id="result"> Previous value: </div>
您将要在localStorage中设置提交的值:
document.getElementById("myForm")
.addEventListener("submit", function () {
var imagePath = document.getElementById("control").value;
localStorage.setItem("path", imagePath);
});
然后在页面加载时检索它:
var imagePath = localStorage.getItem("path");
document.getElementById("result").textContent += imagePath || 'Nothing';