[英]Javascript clock function not running on Rails app
第一次實時,我嘗試在Rails應用程序中使用Javascript,但是警報之外的所有內容似乎對我來說都沒有用。
我想做的就是讓這個簡單的時鍾在我的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
apps / assets / javascripts / sitewide / 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()
函數。 請注意,在示例中,它是通過body
的onload
屬性onload
: <body onload="startTime()">
使用Rails,您可以將其添加到pages.js
文件的末尾:
$(document).on('page:load', function() {
startTime();
});
這將在頁面加載時在函數內執行代碼(並將與Turbolink兼容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.