【发布时间】:2020-10-17 20:40:14
【问题描述】:
我有一个这样的 localStorage 对象:
密钥:jpxun
值:[{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
我有这个 JS 来显示 localStorage 记录:
// get localStorage info
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
// get localStorage length
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
// assign variables for HTML ID elements
var list_items = document.getElementById("usernames");
var plaintext_textarea = document.getElementById("plaintext");
// assign a MyUsernames variable
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
// if localStorage length > 0
if (jpxun_length > 0) {
// loop through localStorage
// get the word part of the username and wrap in list item HTML
// add a link in the list item to delete the localStorage ite via 'deleteById'
for (var i = 0; i < MyUsernames.length; i++) {
// assign a variable to hold the username
var un1 = MyUsernames[i].name;
list_items.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#' onclick='deleteById(this)'>" + un1 + "</a></li>";
// build plaintext version of username list
plaintext_textarea.innerHTML += un1 + "\n";
}
}
// function to delete records from localStorage
var deleteById = function ( self ) {
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
// try to re-do plaintext content
var jpxun2 = JSON.parse(localStorage.getItem('jpxun')) || [];
var MyUsernames2 = JSON.parse(localStorage.getItem("jpxun2"));
for (var i = 0; i < MyUsernames2.length; i++) {
var un1 = MyUsernames[i].name;
plaintext_textarea.innerHTML += un1 + "\n";
}
}
我意识到这有点代码过载...
基本上一切正常 - 我无法开始工作的是,当我从 localStorage 中删除记录时,例如通过单击 HTML 以获取单词的列表项,它可能如下所示:
<li><a id="1" href="#" onclick="deleteById(this)">tippins</a></li>
然后从localStorage中删除该记录,并且包含作为列表项的单词的div id usernames会随着删除的记录被删除而自动刷新。
但是,textarea 中的单词列表不会刷新(即使它是根据 localStorage 中的项目列表构建的)。
这是我在 deleteById 函数中从 localStorage 中删除一个单词时尝试刷新 textarea 单词列表的内容:
// try to re-do plaintext content
var jpxun2 = JSON.parse(localStorage.getItem('jpxun')) || [];
var MyUsernames2 = JSON.parse(localStorage.getItem("jpxun2"));
for (var i = 0; i < MyUsernames2.length; i++) {
var un1 = MyUsernames2[i].name;
plaintext_textarea.innerHTML += un1 + "\n";
}
但是 - 这不起作用,并且 textarea 列表没有更新,删除的单词仍然出现在其中。
更新 textarea 列表的唯一方法是在页面重新加载时,但我希望在从 localStorage 中删除记录时自动更新列表,就像自动更新列表项一样。
【问题讨论】:
-
我不确定我是否正确理解了您的问题...但是How to change the Content of a <textarea> with Javascript 对您有帮助吗?