首页 > 解决方案 > 在 AJAX 更新 Ruby on Rails 6 后,语义 UI 模式不会重新打开

问题描述

当我使用 AJAX 更新记录的表行时。我无法重新打开语义 UI 的模式,但是当我在更新记录之前单击打开模式按钮时 - 这样做没有问题。有没有人经历过这个?在 Rails 中进行 AJAX 更新后,如何让模式重新初始化?奇怪的是按钮的 id 仍然设置,只是在更新记录后没有打开模式。

chart_records_controller.rb

def update

respond_to |format|
   if @chart_record.update(chart_record_params)
   format.js {}
 else
  format.js {}
 end
end

更新.js.erb

document.getElementById('<%= dom_id(@chart_record, 'inline_form') %>').remove()
document.getElementById('<%= dom_id(@chart_record, 'inline_form') %>').innerHTML = "<%= j render @chart_record %>"
document.getElementById('<%= dom_id(@chart_record, 'inline_form') %>').style.display = 'table-row'

_chart_record.html.erb

<div class="divTableCell"><%= link_to chart_record.date %></div>
<div class="divTableCell"><%= link_to chart_record.username %></div>
<div class="divTableCell">
 <button class="ui icon button" id="chart_record_comment_btn_<%= chart_record.id">
</button>

<div class="ui modal chart_record_comment_modal_<%= chart_record.id %>">
  <i class="close icon"></i>
 <div class="p-3">
   <%= simple_form_for(chart_record, url: update_comment_for_chart_record(id: chart_record.id), method: :post, remote: true) do |f| %>
  <%= f.input :comment_body, as: :text, label: "Comment" %>   
  <%= f.submit 'Update Comment', class: 'ui button' %>
<% end %>
 </div>
</div>
</div>

<script>
 // only works before record is updated inline.
 $('#chart_record_btn_<%= chart_record.id' %>').click(function() {
    $('ui.modal.chart_record_comment_modal_<%= chart_record.id %>').modal('show')
  });
</script>

标签: javascriptjqueryruby-on-railsruby

解决方案


我只是用按钮本身的 onclick 参数调用了模式。我认为更新迫使 DOM 进入未就绪状态。看起来很老套,但没有其他方法可以让 JS 重新初始化模态。

<button type="button" onclick="$('ui.modal.chart_record_comment_modal_<%= chart_record.id %>').modal('show')"><i class="icon comment outline"></i></button>

推荐阅读