我无法理解如何将变量传递给模态,以便我可以使用(不是作为表单中的输入)而是在辅助方法中使用。
我看过:Passing data to a bootstrap modal和 How to pass values arguments to modal.show() function in Bootstrap和 Bootstrap JavaScript
链接模式:
<%= link_to "#{comment.fname}", "#commenterModal", :class => "btn commenter", "data-toggle" => "modal", "data-id" => "4"%>
我正在使用 data-id="4"进行测试,但我会传入 Rails 变量 comment.id。
模态:
<div id="commenterModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body" style="background-color: #F5F5F5;">
<div class="row" id="commentId">
<%= getuserprofileofcommenter(commentId).bio %>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>
</div>
</div>
</div>
</div>
</div>
JS:
$(document).ready(function() {
$('#commenterModal').on('show.bs.modal', function(event) {
$("#commentId").val($(event.relatedTarget).data('id'));
});
});
我知道我没有正确理解这一点。但是当我点击 link_to 时,我试图采用这个实例,将变量 (comment.id) 传递给模态,这样我就可以在调用辅助方法“getuserprofileofcommenter(commentId)”时使用它。
任何见解都会有所帮助。谢谢你!
最佳答案
据我了解,您希望每次单击评论链接时都更改模式的内容。
在这种情况下,我通常会借助 Rails ajax。
将模态内容提取到部分 _show_modal.html.erb
<div id="commenterModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body" id="commentUserModal">
<%= getuserprofileofcommenter(@comment.id).bio if @comment.present? %>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
包含 <strong>link_to</strong>
的模板:
<%= link_to comment.fname, show_modal_groups_path(comment_id: comment.id), :class => "btn", remote: true %>
<!-- rendering partial -->
<div id="commentUserModal">
<%= render 'show_modal' %>
</div>
comments_controller.rb
def show_modal
@comment = Comment.find_by_id(params[:comment_id])
respond_to do |format|
format.js {render 'show_modal'}
end
end
评论/show_modal.js.erb
$("#commentUserModal").html("<%= j render 'show_modal' %>");
$("#commenterModal").modal('show');
此代码未经测试。
希望对您有所帮助。
关于javascript - 使用助手中使用的 link_to 模态传递 Rails 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36161900/