我有一个代码:
$(document).ready(function() {
var count = 1;
$("button").click(function() {
var inputVal = $('input').val();
$('div').append("<p>"+ inputVal +"</p>");
localStorage.setItem('pvalue'+count, inputVal);
$("input").replaceWith("<input id='num_" + count++ +"'/>");
})
var local = localStorage.getItem("pvalue"+ count);
$('div').append("<p>"+ local +"</p>");
})
此代码保存输入的所有值,但只显示第一个。我不知道如何在刷新后显示所有保存的 p 标签,有人可以帮助我吗?
HTML:
<body>
<div class='mt-5 text-center'>
<input> <button>Add</button>
</div>
<script src='script.js'></script>
</body>
最佳答案
问题是由于您使用了 count
变量。这在设置数据时很好,但是在重新加载它时 count
将设置回 1
并且您不会明确知道您保存了多少条目。
一个更好的主意是在 localStorage 中存储一个数组,您可以轻松地对其进行添加和检索。试试这个:
$(document).ready(function() {
$("button").click(function() {
var inputVal = $('input').val();
$('div').append("<p>" + inputVal + "</p>");
var pValues = JSON.parse(localStorage.getItem('pvalue')) || [];
pValues.push(inputVal);
localStorage.setItem('pvalue', JSON.stringify(pValues));
})
var pValues = JSON.parse(localStorage.getItem('pvalue')) || [];
var html = pValues.map(function(local) {
return '<p>' + local + '</p>';
}).join('');
$('div').append(html);
})
关于javascript - localStorage + jQuery 自动保存和加载 p,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51496118/