Rails 4 app ...在开发环境中javascript不会被触发,除非页面被刷新 [英] Rails 4 app... in development environment javascript not firing unless page is refreshed
问题描述
所以我的第一个rails4应用程序遇到了一个奇怪的问题,我的页面javascript没有被触发,除非我重新加载页面。
So I am having an odd issue with my first rails4 app where my page javascript is not firing unless I reload the page.
这对我的资产都是如此管道JS和内联content_for JS。
This is true for both my asset pipeline JS and also inline with content_for JS.
在我的/assets/javascripts/cars.js文件中:
in my /assets/javascripts/cars.js file:
$(function(){
$("#car_car_make_id").on("change", function(){
//SET MODELS
$.ajax({
url: "/car_makes/" + $(this).val() + "/car_models",
type: "GET",
dataType: "json",
cache: false
})
.done(function(data) { model_list(data) })
.fail(function() { alert("error"); })
});
});
function model_list(data) {
$("#car_car_model_id").empty();
$.each(data, function(i,v){
$("<option />").val(v.id).text(v.name).appendTo("#car_car_model_id");
});
//ON COMPLETE SHOW
$("#car_model_div").show();
}
内联于content_for的页面:
inline in page with content_for:
<% content_for :head do %>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('yt_vid', {
height: '390',
width: '640',
videoId: '<%= @timeslip.youtube_id %>'
});
}
</script>
<% end %>
如果我刷新页面,这两个都只会触发。
Both of these only fire if i refresh the page.
例如,如果我点击带有youtube视频的页面的链接,它将无法加载。但如果我刷新它会。与资产管道脚本相同,如果我首先重新加载页面,它只会调用我的ajax。
For example, if i click a link to the page with the youtube video it will not load. but if I refresh it will. Same with the asset pipeline script, it only makes my ajax call if i reload the page first.
推荐答案
看起来像一个副作用新的 Turbolinks 功能。当您单击链接时,页面不会被重新加载 - 它只是由AJAX请求加载< body>
。所以:
looks like a side effect of the new Turbolinks feature. When you click a link, the page isn't being reloaded -- it's just having its <body>
loaded by an AJAX request. So:
在第一种情况下, $(函数{...})
未运行因为 document.ready
仅在首页加载时触发,而不是重新加载正文。
In the first case, the $(function{ ... })
isn't being run because document.ready
is only fired on the first page load, not reloading the body.
在第二种情况下,< head>
不会重新加载turbolinks,只是正文。所以你留下旧的< script>
并且不会重新运行!
In the second case, the <head>
isn't reloaded with turbolinks, just the body. So you're left with the old <script>
and it isn't rerun!
检查一些turbolinks的选项,如 jquery.tubrolinks 。
Check some of the options for turbolinks, like jquery.tubrolinks.
这篇关于Rails 4 app ...在开发环境中javascript不会被触发,除非页面被刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!