简体   繁体   中英

Javascript clock function not running on Rails app

First real time I've tried to use Javascript in a Rails app, but nothing outside of alerts seem to be working for me.

What I'm trying to do is get this simple clock to run on my Rails app, pretty much copying the code where I thought it was supposed to go, but nothing's working and all my searches are either too specific or don't seem to work.

I want the clock to be available sitewide but I've also tried organizing it onto specific controllers and their views with the same amount of luck.

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>

You have the JavaScript in place, but you are not actually calling the startTime() function. Note in the example it is called via an onload attribute on body : <body onload="startTime()">

With Rails, you could add this to the end of your pages.js file:

$(document).on('page:load', function() {
  startTime();
});

This will execute the code within the function on page load (and will be compatible with turbolinks).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM