【问题标题】:Javascript clock function not running on Rails appJavascript时钟功能未在Rails应用程序上运行
【发布时间】:2023-03-26 20:18:01
【问题描述】:

我第一次实时尝试在 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

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();,时钟会出现吗?
  • 为什么是的,是的。而且我感觉自己越来越像个新手了。

标签: javascript ruby-on-rails


【解决方案1】:

您已经安装了 JavaScript,但实际上并未调用 startTime() 函数。请注意,在示例中,它是通过 body 上的 onload 属性调用的:&lt;body onload="startTime()"&gt;

使用 Rails,您可以将其添加到 pages.js 文件的末尾:

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

这将在页面加载时执行函数内的代码(并将与 turbolinks 兼容)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2012-05-27
    • 2011-12-29
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多