gpt4 book ai didi

javascript - 允许用户在不刷新页面的情况下发表多条评论

转载 作者:行者123 更新时间:2023-11-29 21:30:12 25 4
gpt4 key购买 nike

在我的 Rails 应用程序中,用户可以对帖子发表评论。当用户提交评论时,此代码将从 CommentsController 运行:

def create
@comment = Comment.new(comment_params)
@comment.user_id = current_user.id
@matchup = Post.find(comment_params[:post_id])
if @comment.save
respond_to do |format|
format.js
end
end
end

我设置了它,所以当创建评论时,我在 comments/create.js.erb 中运行这段代码

$("#comment-form-<%= @post.id %>").replaceWith("<%= j render partial: 'comments/comment_form', locals: {post: @post} %>"),
$("#new-comment-<%= @post.id %>").replaceWith("<%= j render partial: 'comments/comment', locals: {post: @post, comment: @comment} %>");

这将重新呈现评论表单并将用户的新评论呈现在评论列表的顶部。它非常适合第一条评论。

但是,如果用户不刷新页面并留下第二条评论,则此代码不起作用。第二条评论已创建,但仅在刷新页面时才会出现。说到 JS,我是个新手。我错过了什么?

最佳答案

创建新评论时,您不需要替换原来的评论dom,您可能需要在新评论之前/之前/之后附加/添加新评论。尝试更改:

$("#new-comment-<%= @post.id %>").replaceWith("<%= j render partial: 'comments/comment', locals: {post: @post, comment: @comment} %>"

收件人:

 $("#new-comment-<%= @post.id %>").before("<%= j render partial: 'comments/comment', locals: {post: @post, comment: @comment} %>"

关于javascript - 允许用户在不刷新页面的情况下发表多条评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com