【问题标题】:Opening show page in a modal with updating url in address bar as in instagram example using Ruby on Rails 5以模式打开显示页面,并在地址栏中更新 url,如使用 Ruby on Rails 5 的 instagram 示例
【发布时间】:2017-12-01 15:14:12
【问题描述】:

我正在尝试在我的 Ruby on Rails 5 项目中实现附加行为。

单击索引中的帖子会打开模式而不是链接到显示页面,但还会使用帖子网址更新浏览器的地址栏。

对于模态,我使用 jquery-modal http://jquerymodal.com不使用 Bootstrap

我的示例代码如下↓


目前我有下面的代码。模式工作正常,但它不会更新 url。

index.html.erb

<%= link_to image_tag(post.image_url.to_s), post_path(post), remote: true %>

_post_modal.html.erb

<div id="post-modal" class="modal fade" role="dialog">

  <div class="modal-dialog modal-lg">
    <div class="modal-content flex flex-wrap items-start w-100 postmodal">

      <div class="w-75-l">
        <a href="#close" rel="modal:close" title="Close"><%= image_tag @post.image_url.to_s %></a>
      </div>

      <div class="w-25-l">

        <a href="#close" rel="modal:close" title="Close" class="btn-closemodal">X</a>

        <h1><%= @post.title %></h1>

      </div>
    </div>
  </div>
</div>

post_controller.rb

  def show

    @post = Post.friendly.find(params[:id])

    respond_to do |format|
      format.js
    end
  end

show.js.erb

$('#post-content').html("<%= j render 'post_modal', post: @post %>");
$('#post-modal').modal('show');

我在显示页面收到此错误

【问题讨论】:

    标签: javascript jquery ruby-on-rails modal-dialog ruby-on-rails-5


    【解决方案1】:

    将此行添加到 show.js.erb 解决了问题

    history.replaceState({}, "<%= @post.title %>", "<%= request.original_url %>");
    

    或者如果您不想在模式打开时更改 url。将此行添加到 show.js.erb

    history.pushState({}, "Your Title", "<%= your_current_url %>");
    

    【讨论】:

    • 感谢这对我有用。但是当我退出模式时,url 不会恢复。关于如何解决这个问题的任何想法?
    【解决方案2】:

    在 ajax:成功检索您的模态部分时,您可以使用编辑导航栏

    function editURL(page, title, url) {
      window.history.pushState(page, title, url);
    }
    

    类似

    $("#get-show").on("ajax:success", function(e) {
       editURL("pagename", "pagetitle", "url")
    })
    

    编辑

    如果你想让你的后退按钮在浏览器中工作,你必须在准备好的文档上添加以下代码。

    window.addEventListener("popstate", function(e) {
       window.location.href = location.href;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-21
      • 2016-07-28
      • 1970-01-01
      • 2011-03-15
      • 2013-03-31
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多