您好,如标题中所述,我正在尝试找到一种方法,以将createElement(“ p”)及其存储的值保留在ID为“ content”的本地存储数组中。即使按刷新后仍会显示在页面上。
此代码的目的是制作活动供稿或类似消息公告? (更像Twitter)
但是纯粹是使用Javascript并将内容按数组顺序放置。
顶部为新“帖子”,底部为旧帖子。每次点击
<div class="tweet-box">
<textarea id="tweet-input" placeholder="What's on your mind?" maxlength="320"></textarea>
<button type="button" class="post" style="float:right;" onclick="getTextinput()">Post</button>
<span class="danger">320</span>
</div>
</div>
<div class="w3-container w3-teal">
<div class="story-box">
<div class="avatar-container"><img src="images/Andi.jpg" alt="Avatar" class="avatar"></div>
<div id="content">
</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", createStoryDatabase);
var StoryDatabase;
function createStoryDatabase() {
StoryDatabase = localStorage.getItem("StoryDatabase");
if (StoryDatabase == null) {
StoryDatabase = [];
} else {
StoryDatabase = JSON.parse(StoryDatabase);
}
}
//Function that gets Text input & prints out to a P
function post() {
getTextinput
}
function getTextinput() {
//Gets data or input from text Area
var inputText = document.getElementById('tweet-input').value;
var objText = {
"tweet-input": inputText
};
StoryDatabase.push(objText);
localStorage.setItem("StoryDatabase", JSON.stringify(StoryDatabase));
//to print out the input of user into <p>
var Node = document.createElement("p");
Node.innerHTML = inputText;
document.getElementById("content").appendChild(Node);
}
function displayAll() {
var obj = localStorage["StoryDatabase"];
if (obj != null) {
obj = JSON.parse(obj);
for (var i = 0; i < obj.length; i++) {
var textBefore = obj[i].tweet - input;
var Node = document.createElement("p");
Node.innerHTML = textBefore;
document.getElementById("content").appendChild(Node);
}
}
}
</script>