我第一次实时尝试在Rails应用中使用Javascript,但警报之外的任何内容似乎都不适用于我。
我想要做的就是让这个simple clock在我的Rails应用程序上运行,几乎将代码复制到我认为它应该去的地方,但没有任何工作和所有我的搜索要么太具体,要么似乎不起作用。
我希望时钟可以在整个网站上使用,但我也尝试将它组织到特定的控制器和他们的观点上,运气相同。
的application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree ./sitewide
应用/资产/ Javascript角/站点范围/ pages.js
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Clawk</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= render 'shared/navbar' %>
<div class="container-fluid">
<%= render 'shared/sidebar' %>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div id="txt"></div>
<%= yield %>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
您已准备好JavaScript,但实际上并未调用startTime()
函数。请注意,在示例中,它是通过onload
上的body
属性调用的:<body onload="startTime()">
使用Rails,您可以将其添加到pages.js
文件的末尾:
$(document).on('page:load', function() {
startTime();
});
这将在页面加载时执行函数内的代码(并且将与turbolinks兼容)。