我的rails应用程序中的模板在第一次加载javascript代码时通过单击主页中的链接来执行。它只在从链接访问时才会发生,而且只是第一次访问。我不知道为什么会这样。有帮助吗?这是代码。
主页:
#app/views/static_pages/home.html.erb
#...
<%= link_to "Nofify an absence", new_cancellation_path %>
这是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
}
});
});
应该执行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>
我已尝试将//= require cancellations_new
添加到app/assets/javascripts/application.js
但没有任何改进
修改
我做了一些研究,跟随@radubogdan领导,我发现Turbolinks负责#&#34;奇怪的&#34; Javascript的行为。如果在应用程序中激活了Turbolinks,则会从Ajax请求加载<a>
元素,然后使用该内容修改HTML的<body>
。由于加载DOM的方式不是通常的,因此编写在
$(document).ready(){...}
无法工作。如果您希望Javascript像往常一样运行,则可能需要更改
$(document).ready(){...}
到
$(document).on("page:change", function() {
// some more code.
});
答案 0 :(得分:6)
我认为turbolinks是个问题。你有没有尝试停用它?
从application.js
和layout.html.erb
中使用样式表链接标记将其删除。
如果它没有turbolinks,那么你应该检查如何使用
$(document).on('page:load', .....)
由于
答案 1 :(得分:5)
只需添加application.html.erb
<body data-no-turbolink="true" >
# your content
</body>
或强>
将此添加到您的gem文件
gem 'jquery-turbolinks'
两种方式都可以按照您的要求运作。