创建评论并将其添加到评论框中



这里绝对是初学者程序员。我正在尝试创建一个评论框,无论你在评论中键入什么,都将存储在另一个div中。我希望它将注释存储在#comment boxdiv中,当您输入另一个注释时,它会将其存储在下面。这是我到目前为止的代码

<div class="container">
<h2>Leave us a comment</h2>
<form>
<textarea id="" placeholder="Add Your Comment" value=" "></textarea>
<div class="btn">
<input id="submit" type="submit" value="Comment">
<button id="clear">  
&#128591;</button>
</div> 
</form>
</div>
<div class="comments">
<h2>Comments</h2>
<div id="comment-box" value="submit">
</div>
</div>

我的JS是

const field = document.querySelector('textarea');
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const comments = document.getElementById('comment-box')
field.onfocus = function(){
this.setAttribute('placeholder','')
this.style.borderColor = '#333'
btn.style.display = 'block'
} // when clicking on this, placeholder changes into ' '.
field.onblur = function(){
this.setAttribute('placeholder',backUp)
} //click away, placeholder returns
clear.onclick = function(){
btn.style.display = 'none';
field.value = ' '
submit.onclick = function(){
submit.style.display = 'none';
const content = document.createTextNode(field.value)
comments.appendChild(content)

伙计们,我哪里错了?如有任何反馈,我们将不胜感激。谢谢

  • 您可以使用一个数组来存储注释,以及一个基于数组生成html注释列表的函数
  • 在提交并清除时,应使用event.preventDefault();防止表单提交到其他页面
  • 在提交和清除时,您可以操作数组并调用html生成函数来重新创建commets框内容

const field = document.querySelector('textarea');
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const comments = document.getElementById('comment-box');
// array to store the comments
const comments_arr = [];
// to generate html list based on comments array
const display_comments = () => {
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
clear.onclick = function(event){
event.preventDefault();
// reset the array  
comments_arr.length = 0;
// re-genrate the comment html list
display_comments();
}
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length > 0){ // if there is content
// add the comment to the array
comments_arr.push(content);
// re-genrate the comment html list
display_comments();
// reset the textArea content 
field.value = '';
}
}
<div class="container">
<h2>Leave us a comment</h2>
<form>
<textarea id="" placeholder="Add Your Comment" value=" "></textarea>
<div class="btn">
<input id="submit" type="submit" value="Comment">
<button id="clear">  
&#128591;</button>
</div> 
</form>
</div>
<div class="comments">
<h2>Comments</h2>
<div id="comment-box">
</div>
</div>

最新更新