当我从链接访问页面时,Javascript第一次没有执行

fel*_*lix 10 javascript ruby-on-rails turbolinks

我的rails应用程序中有一个模板,通过单击我主页中的链接,第一次加载时不会执行javascript代码.只有在第一次从链接访问它时才会发生这种情况.我不知道为什么会这样.有帮助吗?这是代码.

主页:

#app/views/static_pages/home.html.erb
#...
<%= link_to "Nofify an absence", new_cancellation_path %>
Run Code Online (Sandbox Code Playgroud)

这是Javascript文件:

//app/assets/javascripts/cancellations_new.js

var validateDateTime = function(){
// some other code that returns true or false
  }
  $(document).ready(function(){
    $("#new_cancellation").submit(function(event){
      event.preventDefault();
      if (validateDateTime()) {
        alert("Some alert");
      }
      else { 
        // some more code 
      }
    }); 
  }); 
Run Code Online (Sandbox Code Playgroud)

以及应该执行javascript的模板:

#app/views/cancellations/new.erb

<%= provide(:title, "Notify an absence")%>
<div class="row">
<div class="span3 offset4">
  <h3> Notify an absence </h3>

  <%= form_for @cancellation, :id => "new_cancellation" do |f| %>
    <%= render 'shared/error_messages' %>
    <% # some form elements...%>
    <%= f.submit "Send", class: "btn btn-primary"%>        
  <% end %>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我已经尝试添加//= require cancellations_newapp/assets/javascripts/application.js没有改进

编辑

我做了一些研究,跟随@radubogdan领导,我发现Turbolinks负责Javascript的"奇怪"行为.如果在应用程序中激活了Turbolinks <a>,则会从Ajax请求加载元素,然后使用内容修改<body>HTML.因为加载DOM的方式不是通常的,编写在其中的代码

$(document).ready(){...}

除非页面完全重新加载(例如刷新浏览器),否则将无法工作.如果您希望Javascript像往常一样运行,则可能需要更改您的

$(document).ready(){...}

$(document).on("page:change", function() { // some more code. });

你可以找到关于此主题的一些更多的信息在这里

rad*_*dan 7

我认为turbolinks是个问题.你有没有尝试停用它?

从中删除application.js,并从layout.html.erb那里您使用样式表的链接标签.

如果它没有turbolinks工作,那么你应该检查如何使用

$(document).on('page:load', .....)

谢谢


小智 5

只需加入你的 application.html.erb

<body data-no-turbolink="true" >
  # your content
</body>
Run Code Online (Sandbox Code Playgroud)

要么

将其添加到您的gem文件中

gem 'jquery-turbolinks'
Run Code Online (Sandbox Code Playgroud)

两种方式都可以按照您的要求运作.