【问题标题】:Adding Comments to a Post in JS在 JS 中为帖子添加评论
【发布时间】: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


    【解决方案1】:

    commentForm.innerText = renderCommentForm(button.id)

    应该是 commentForm.innerHtml = renderCommentForm(button.id)

    https://www.w3schools.com/jsref/prop_html_innerhtml.asp

    【讨论】:

    • 谢谢,我改成html了,还是没有渲染...
    • 谢谢,当我将其更改为commentForm.innerHTML = renderCommentForm(button.id) 时,该部分起作用了。但是由于某种原因仍未创建 blogPostCard 'div'。
    • @Echelon1089 很好地解决了我会首先清理你的变量的问题。例如,您将 postContent 声明为 appendChild(newPostContent) ,然后在 const newBlog = blogPostCard.appendChild(postTitle, postContent) 中尝试再次 appendChild 这个常量。当在实际页面上时,我还会尝试将该 JS 放入浏览器控制台中,以查看它是否会引发任何错误。修复可能如下所示: const postContent = "

      Lorem Ipsum

      "; blogPostCard.appendChild(postContent);众多“无用”的常量和函数对调试没有多大帮助。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2013-12-02
    • 1970-01-01
    相关资源
    最近更新 更多