【发布时间】:2020-10-30 06:01:37
【问题描述】:
我正在尝试添加一种方法来为我创建的每个博客发表评论。我的想法是把我的 postTitle 和 postContent 包装在一个 div 中。然后传入可以访问博客 ID 的commentForm 的 HTML 表单 js。
问题在于 blogCard.appendChild(postTitle, postContent) 实际上并没有将属性包装在 div 中,而 renderCommentForm() 将字符串返回到前端而不是 HTML。
感谢您提供的任何建议,以了解如何通过 forEach 为每篇博文创建评论。
const postContainer = document.querySelector("#posts-container")
console.log(posts)
posts.data.forEach(function(post){
const newPostTitle = document.createElement('h4')
newPostTitle.innerText = post.attributes.title
const postTitle = postContainer.appendChild(newPostTitle)
const newPostContent = document.createElement('p')
newPostContent.innerText = post.attributes.content
const postContent = postContainer.appendChild(newPostContent)
const button = document.createElement('button')
button.id= `${post.id}`
button.innerText = 'Leave a Comment'
postContainer.appendChild(button)
const blogPostCard = document.createElement('div')
const newBlog = blogPostCard.appendChild(postTitle, postContent)
postContainer.appendChild(newBlog)
const commentForm = document.createElement('div')
commentForm.innerText = renderCommentForm(button.id)
postContainer.appendChild(commentForm)
button.addEventListener('click', function(e){
renderCommentForm(button.id)
});
function renderCommentForm(postId){
console.log(postId)
return (
`<form id='comment-form' class="">
<input id='comment' type="text" name='comment' value='' placeholder= 'Comment Here'/>
</form>`)
}
【问题讨论】:
标签: javascript html comments blogs