我在我的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导致JavaScript的“奇怪”行为。如果您在应用程序中激活了Turbolinks,则会从Ajax请求中加载元素,然后使用内容修改HTML的。由于DOM加载方式不是通常的方式,因此写在 $(document).ready(){...}
中的代码除非完全重新加载页面(例如刷新浏览器),否则不起作用。如果您希望JavaScript像往常一样运行,则可能需要将
$(document).ready(){...}
更改为
$(document).on("page:change", function() {
// some more code.
});