在 jQuery 中插入一个 CSS id

Inserting a CSS id into jQuery

本文关键字:一个 CSS id jQuery 插入      更新时间:2023-09-26

我有一个基本的注释语句,底部是一个添加新注释的表单。 目标很简单,但我已经尝试了很多,但无法让它工作。 当有人在表单中提交评论时,我希望该评论显示在上方,并让它使用 jQuery 将表单向下移动。 这工作正常,但我有 2 个问题。

  1. 我需要jQuery显示的新注释来继承一个名为triangle-right的CSS类。

  2. 我需要清除表单,它会在提交后保留最后一条评论。

这是jQuery。 同样,我需要 @comment.recommendation 使用 CSS 类三角形右边显示并清除表单。 #newrec 是形式。

$('#newrec').before('<%= escape_javascript(@comment.recommendation) %>');

如果有帮助,这里是视图。

<% recs.each do |r| %>
    <% name = User.find_by(:id => r.user_id)%>
    <p class = "triangle-right" id ="comment_<%=r.id%>">
      <b><%=name.first_name.capitalize %> <%=name.last_name.capitalize %></b>:    <%=r.recommendation %></br></br>
    <%= link_to '<i class="icon-edit"></i>'.html_safe, edit_comment_url(r),class:"btn btn-warning" if current_user.present? && r.user_id == current_user.id %>
    <%= link_to '<i class="icon-trash"></i>'.html_safe, comment_url(r), class:"btn btn-danger", method: 'delete', remote: true if current_user.present? && r.user_id == current_user.id %>
    </p>
  <%end%>
    <!-- LIST OF RECOMMENDATIONS IS ABOVE -->
    <!-- FORM FOR RECS BELOW -->
  <div>
    <%= form_tag(commentpost_url, id: "newrec", method: 'post', remote: true) do %>
      <h4><%= "Give your recommendations:" if current_user.present? %></h4>
      <%= text_area_tag :recommendation, nil, class: "rectextarea", id: "new_rec" if current_user.present? %>
      <%= hidden_field_tag :trip_detail_id, d.id %>
      <%= hidden_field_tag :user_id, current_user.id if current_user.present?%>
    <div>
      <% if current_user.present? && @trip.userid == current_user.id %>
        <%= submit_tag 'Add Comment', class: "btn btn-large btn-success" if current_user.present? %>
      <%else%>
        <%= submit_tag 'Submit Recs!', class: "btn btn-large btn-success" if current_user.present? %>
      <%end%>
    </div>
   <% end %>

最后是控制器

def create
@comment = Comment.new
@comment.recommendation = params[:recommendation]
@comment.trip_detail_id = params[:trip_detail_id]
@comment.user_id = params[:user_id]
if @comment.save
  respond_to do |format|
   format.html { redirect_to :back, notice: 'Rec was successfully created.' }
   format.json { render action: 'show', status: :created, location: @comment }
   format.js
  end
else
  render 'new'
end

结束

谢谢!

解决方案是:

  1. 如果要添加新注释以显示,则注释应为列表。相应地修改此内容。
  2. 提取您的注释显示部分,<li>部分到部分。
  3. 将表单部分提取为部分
  4. 在视图中渲染这些部分模板以替换以前的零件。
  5. 在 js 中再次渲染这两个部分

像这样的伪js代码

$('ul#comments').append('<%=j render partial: "comment", locals: {comment: @comment}')
$('#comment_form').html('<%=j render partial: "comment_form", 
                                              locals: {comment: Comment.new)') 

附言你的代码真的需要改进。太多的逻辑观点,太多非常规的东西。