如何使用javascript在网页重新加载后保留已创建的元素

huangapple go评论65阅读模式
英文:

How to keep created elements on the web page after the page reload using javascript

问题

我正在尝试为我弟弟开发一个网页。这个网页是一个用户互动页面,用户可以添加评论。我遇到了问题,在使用for.Each函数创建了用户评论后,无法在页面刷新后保留这些已创建的评论。我知道我必须使用"local.storage"函数,但我还没有找到解决方案:'-(有好心人可以帮助我吗?谢谢!

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Comments</title>
  <link rel="stylesheet" href="css/reset.css">
  <link rel="stylesheet" href="css/nmComments.css">
</head>

<body>

  <header class="header">
    <a class="logo" href="#">
      <p>Comments page</p>
    </a>
    <button class="button--menu">
      <ion-icon class="menu--icon" name="menu"></ion-icon>
    </button>
  </header>

  <main>
    <div class="main">
      <form class="comment--form" action="#" id="form">
        <h1 class="interact">Interact with us!<br>Leave your comment here</h1>

        <div>
          <label for="comment--text">Your comment:</label><br>
          <textarea class="comment--box" type="text" required id="textarea" placeholder="Add your comment"
            maxlength="150"></textarea>
        </div>
        <button class="form--button" id="submit">Paste it</button>
      </form>
    </div>

    <h2 class="comments--h2">Comments</h2>
    <div id="comment--area" class="comment--area">
      <!-- <div class="client--box">
        <div id="name-box"></div>
      <div id="comment-box">
        </div>
        <button id="clear" class="hidden">
          &#128591;</button>
      </div> -->
    </div>
  </main>

  <footer>
    <div class="footer"></div>
  </footer>
  <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>

  <script language="Javascript">
const field = document.getElementById('textarea');

const submit = document.getElementById('submit');

const createComments = document.getElementById('comment--area');

const comments_arr = [];


submit.onclick = function(event){
    event.preventDefault();
    const content = field.value;
    if(content.length > 0){ // 如果有内容,将评论添加到数组中
    
      comments_arr.push(content);

      // 重新生成评论的HTML列表

      display_comments();
      
      // 重置文本区域和数组内容
      comments_arr.length = 0;
      field.value = '';
      
    }
}

const display_comments = () => {
  let box = document.createElement('textarea');
  box.classList.add('comment--box');
  createComments.append(box);
  let list = '';
   comments_arr.forEach(comment =>  {
    list +=  comment;
  })

  box.append(list);
  box.innerHTML = list;
}
</script>
</body>

</html>
英文:

I am trying to develop a web page for my little brother.It's about a user interactive page for adding comments by the users.I am having trouble, after created the user comments with a for.Each function, in keeping those created comments on the web page after the page refresh.I know that i have to use "local.storage" function but i didn't find any solution yet :'-(Can any good person help me please??Thank you!

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;Comments&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/reset.css&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/nmComments.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;header class=&quot;header&quot;&gt;
&lt;a class=&quot;logo&quot; href=&quot;#&quot;&gt;
&lt;p&gt;Comments page&lt;/p&gt;
&lt;/a&gt;
&lt;button class=&quot;button--menu&quot;&gt;
&lt;ion-icon class=&quot;menu--icon&quot; name=&quot;menu&quot;&gt;&lt;/ion-icon&gt;
&lt;/button&gt;
&lt;/header&gt;
&lt;main&gt;
&lt;div class=&quot;main&quot;&gt;
&lt;form class=&quot;comment--form&quot; action=&quot;#&quot; id=&quot;form&quot;&gt;
&lt;h1 class=&quot;interact&quot;&gt;Interact with us!&lt;br&gt;Leave your comment here&lt;/h1&gt;
&lt;div&gt;
&lt;label for=&quot;comment--text&quot;&gt;Your comment:&lt;/label&gt;&lt;br&gt;
&lt;textarea class=&quot;comment--box&quot; type=&quot;text&quot; required id=&quot;textarea&quot; placeholder=&quot;Add your comment&quot;
maxlength=&quot;150&quot;&gt;&lt;/textarea&gt;
&lt;/div&gt;
&lt;button class=&quot;form--button&quot; id=&quot;submit&quot;&gt;Paste it&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;h2 class=&quot;comments--h2&quot;&gt;Comments&lt;/h2&gt;
&lt;div id=&quot;comment--area&quot; class=&quot;comment--area&quot;&gt;
&lt;!-- &lt;div class=&quot;client--box&quot;&gt;
&lt;div id=&quot;name-box&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;comment-box&quot;&gt;
&lt;/div&gt;
&lt;button id=&quot;clear&quot; class=&quot;hidden&quot;&gt;
&amp;#128591;&lt;/button&gt;
&lt;/div&gt; --&gt;
&lt;/div&gt;
&lt;/main&gt;
&lt;footer&gt;
&lt;div class=&quot;footer&quot;&gt;&lt;/div&gt;
&lt;/footer&gt;
&lt;script type=&quot;module&quot; src=&quot;https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js&quot;&gt;&lt;/script&gt;
&lt;script nomodule src=&quot;https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js&quot;&gt;&lt;/script&gt;
&lt;script language=&quot;Javascript&quot;&gt;
const field = document.getElementById(&#39;textarea&#39;);
const submit = document.getElementById(&#39;submit&#39;);
const createComments = document.getElementById(&#39;comment--area&#39;);
const comments_arr = [];
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length &gt; 0){ // if there is content add the comment to the array
comments_arr.push(content);
// re-generate the comment html list
display_comments();
// reset the textArea and arrey contents
comments_arr.length = 0;
field.value = &#39;&#39;;
}
}
const display_comments = ()=&gt; {
let box = document.createElement(&#39;textarea&#39;);
box.classList.add(&#39;comment--box&#39;);
createComments.append(box);
let list = &#39;&#39;;
comments_arr.forEach(comment =&gt;  {
list +=  comment;
})
box.append(list);
box.innerHTML = list;
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

答案1

得分: 0

以下是您需要的翻译部分:

"Normally is better if you used a database but since you don't know how to, you can do it like this with the help of localStorage"

通常最好使用数据库,但由于您不知道如何使用,您可以像这样使用localStorage来做:

"This line will tell your code that your initial arrays value is either whatever was store in localstorage or an empty array if nothing was stored yet"

这行代码将告诉您的代码,初始数组的值要么是存储在本地存储中的内容,要么是一个空数组(如果尚未存储任何内容):

"let comments_arr = JSON.parse(localStorage.getItem("comments")) || [];"

让comments_arr等于JSON.parse(localStorage.getItem("comments"))或空数组;

"so whenever you press the button you will push a new value to your array and save the updated array to your storage with this:"

所以每当您按下按钮时,您将向数组中push一个新值,并使用以下代码将更新后的数组保存到存储中:

"comments_arr.push(field.value);//push value to array"

comments_arr.push(field.value);//将值添加到数组中

"window.localStorage.setItem("comments", JSON.stringify(comments_arr));//save to storage"

window.localStorage.setItem("comments", JSON.stringify(comments_arr));//保存到存储中

"Finally when you need to show all comments just loop thru your array and create a textarea for each comment you have then proceed to append like you were doing to your createComments element."

最后,当您需要显示所有评论时,只需遍历您的数组并为每个评论创建一个文本区域,然后继续像您对createComments元素所做的那样追加。

英文:

I believe this is what you need:

Normally is better if you used a database but since you don't know how to, you can do it like this with the help of localStorage

This line will tell your code that your initial arrays value is either whatever was store in localstorage or an empty array if nothing was stored yet

let comments_arr = JSON.parse(localStorage.getItem(&quot;comments&quot;)) || [];

so whenever you press the button you will push a new value to your array and save the updated array to your storage with this:

comments_arr.push(field.value);//push value to array
window.localStorage.setItem(&quot;comments&quot;, JSON.stringify(comments_arr));//save to storage

Finally when you need to show all comments just loop thru your array and create a textarea for each comment you have then proceed to append like you were doing to your createComments element.

This is how the final code will look:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const submit = document.getElementById(&#39;submit&#39;);
const createComments = document.getElementById(&#39;comment--area&#39;);
let comments_arr = JSON.parse(localStorage.getItem(&quot;comments&quot;)) || [];
display_comments();
//window.localStorage.clear(comments_arr);
submit.onclick = function(event) {
let field = document.getElementById(&#39;textarea&#39;);
event.preventDefault();
if (field.value.length &gt; 0) { // if there is content add the comment to the array
comments_arr.push(field.value);
window.localStorage.setItem(&quot;comments&quot;, JSON.stringify(comments_arr));
// re-generate the comment html list
display_comments();
field.value = &#39;&#39;;
}
}
function display_comments() {
let box;
createComments.innerHTML = &#39;&#39;; //reset DOM
for (let i = 0; i &lt; comments_arr.length; i++) {
box = document.createElement(&#39;textarea&#39;);
box.classList.add(&#39;comment--box&#39;);
box.value = comments_arr[i];
createComments.append(box);
}
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;Comments&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/reset.css&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;css/nmComments.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;header class=&quot;header&quot;&gt;
&lt;a class=&quot;logo&quot; href=&quot;#&quot;&gt;
&lt;p&gt;Comments page&lt;/p&gt;
&lt;/a&gt;
&lt;button class=&quot;button--menu&quot;&gt;
&lt;ion-icon class=&quot;menu--icon&quot; name=&quot;menu&quot;&gt;&lt;/ion-icon&gt;
&lt;/button&gt;
&lt;/header&gt;
&lt;main&gt;
&lt;div class=&quot;main&quot;&gt;
&lt;form class=&quot;comment--form&quot; action=&quot;#&quot; id=&quot;form&quot;&gt;
&lt;h1 class=&quot;interact&quot;&gt;Interact with us!&lt;br&gt;Leave your comment here&lt;/h1&gt;
&lt;div&gt;
&lt;label for=&quot;comment--text&quot;&gt;Your comment:&lt;/label&gt;&lt;br&gt;
&lt;textarea class=&quot;comment--box&quot; type=&quot;text&quot; required id=&quot;textarea&quot; placeholder=&quot;Add your comment&quot; maxlength=&quot;150&quot;&gt;&lt;/textarea&gt;
&lt;/div&gt;
&lt;button class=&quot;form--button&quot; id=&quot;submit&quot;&gt;Paste it&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;h2 class=&quot;comments--h2&quot;&gt;Comments&lt;/h2&gt;
&lt;div id=&quot;comment--area&quot; class=&quot;comment--area&quot;&gt;
&lt;!-- &lt;div class=&quot;client--box&quot;&gt;
&lt;div id=&quot;name-box&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;comment-box&quot;&gt;
&lt;/div&gt;
&lt;button id=&quot;clear&quot; class=&quot;hidden&quot;&gt;
&amp;#128591;&lt;/button&gt;
&lt;/div&gt; --&gt;
&lt;/div&gt;
&lt;/main&gt;
&lt;footer&gt;
&lt;div class=&quot;footer&quot;&gt;&lt;/div&gt;
&lt;/footer&gt;
&lt;script type=&quot;module&quot; src=&quot;https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js&quot;&gt;&lt;/script&gt;
&lt;script nomodule src=&quot;https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js&quot;&gt;&lt;/script&gt;
&lt;script language=&quot;Javascript&quot;&gt;
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月4日 23:49:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定