JavaScript时钟函数未在Rails应用程序上运行
问题描述:
第一次实时尝试在Rails应用程序中使用JavaScript,但警报外没有任何东西似乎对我有用。JavaScript时钟函数未在Rails应用程序上运行
我想要做的就是让这个simple clock在我的Rails应用上运行,几乎复制了我认为它应该去的代码,但没有任何工作,所有我的搜索或者太具体或不' t似乎工作。
我希望时钟在站点范围内可用,但我也尝试将它组织到特定的控制器和他们的视图上,运气相同。
的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>
答
您已经有了JavaScript,但实际上并没有调用startTime()
函数。注意:在本例中是通过onload
属性呼吁body
:<body onload="startTime()">
使用Rails,你可以添加到您的pages.js
文件的末尾:
这将在函数中的执行代码页面加载(并将与turbolinks兼容)。
如果您在JavaScript控制台中运行'startTime();',时钟是否显示? –
为什么是的,是的。第二,我越来越像新手了。 – user2965831