简体   繁体   English

Ruby on Rails DOM更新仅在页面重新加载后有效

[英]Ruby on Rails DOM updates only work after page reload

I'm updating a class name for the html element depending on the current route. 我正在根据当前路由更新html元素的类名称。 I also have some jquery to display a menu when an element is clicked. 当单击一个元素时,我还有一些jquery显示菜单。 When I'm on the home page the html class is correctly added to the html element and the menu is correctly displayed when clicked. 当我进入主页时,html类已正确添加到html元素中,并且单击后可正确显示菜单。 However, when I navigate to another route by clicking the nav link the route changes correctly but the html class name is not updated and the jquery doesn't fire anymore. 但是,当我通过单击导航链接导航到另一条路线时,该路线会正确更改,但是html类名称未更新,并且jquery不再触发。

application_helper.rb application_helper.rb

  def html_class(class_name)
    content_for(:html_class) { class_name }
  end 

application.html.erb application.html.erb

<html class="<%= yield(:html_class) || '' %>"> <!-- class is only updated on page reload -->

home.html.erb home.html.erb

<% html_class 'nail' %>

projects/index.html.erb 项目/ index.html.erb

<!-- no html_class provided, should default to '' -->
<div class="row projects">
  <% @projects.each do |project| %>
    <%= render project %>
  <% end %>
</div>

site.js site.js

// when route changes page must reload to fire //当路线更改页面必须重新加载以触发时

$(function() {
  $('#initials').click(function() {
    $('.slider, .nav-btn').toggleClass('closed');
  })
});

Try wrapping your jQuery with the below. 尝试使用以下包装您的jQuery。 The issue is likely caused by Turbolinks which loads pages that you click on with AJAX to speed it up. 该问题可能是由于Turbolinks加载了您使用AJAX单击以加快速度的页面。 So this wrapper tells the Javascript to fire on the turbolinks load instead of on a full page refresh. 因此,此包装器告诉Javascript在Turbolinks加载时触发,而不是在刷新整个页面时触发。

$(document).on('turbolinks:load', function() {
  $('#initials').click(function() {
    $('.slider, .nav-btn').toggleClass('closed');
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM