![](/img/trans.png)
[英]javaScript onClick doesn't work when executed from page loaded inside a DIV on another page
[英]Javascript doesn't get executed the first time when I access a page from a link
我的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请求加载<a>
元素,然后使用该内容修改HTML的<body>
。 因为加载DOM的方式不是通常的,编写在其中的代码
$(document).ready(){...}
除非页面完全重新加载(例如刷新浏览器),否则将无法工作。 如果您希望Javascript像往常一样运行,则可能需要更改您的
$(document).ready(){...}
至
$(document).on("page:change", function() { // some more code. });
我认为turbolinks是个问题。 你有没有尝试停用它?
从application.js
和layout.html.erb
中删除它,您可以在其中使用样式表链接标记。
如果它没有turbolinks工作,那么你应该检查如何使用
$(document).on('page:load', .....)
谢谢
只需添加您的application.html.erb
<body data-no-turbolink="true" >
# your content
</body>
要么
将其添加到您的gem文件中
gem 'jquery-turbolinks'
两种方式都可以按照您的要求运作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.