如何从 html.erb 调用 JavaScript 函数 [英] How do I call a JavaScript function from an html.erb

查看:36
本文介绍了如何从 html.erb 调用 JavaScript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 html.erb 调用 JavaScript 函数

How do I call a JavaScript function from html.erb

application.js

function displayClock() {
  var digital = new Date();
  var hours = digital.getHours();
  var minutes = digital.getMinutes();
  var seconds = digital.getSeconds();
  var amOrPm = 'AM';
  if (hours > 11) amOrPm = 'PM';
  if (hours > 12) hours = hours - 12;
  if (hours == 0) hours = 12;
  if (minutes <= 9) minutes = '0' + minutes;
  if (seconds <= 9) seconds = '0' + seconds;
  dispTime = '<b>'+hours + ':' + minutes + ':' + seconds + ' ' + amOrPm+'</b>';
  document.getElementById('time').innerHTML = dispTime;
  setTimeout('displayClock()', 1000);
}

并在 home.html.erb

displayClock();

但它不是调用函数!

推荐答案

你可能需要使用适当的标签来表明你正在编写 JS 代码:

You probably need to use proper tag to indicate that you're writing JS code:

<script type="text/javascript">
  displayClock();
</script>

另外,由于您可能使用 jQuery(它在 Rails 中是默认的),您可能需要确保在加载整个文档后调用该函数:

Plus, since you probably use jQuery (it's default in Rails), you may want to make sure the function is called after whole document is loaded:

<script type="text/javascript">
  $(document).load(function(){
    displayClock();
  });
</script>

我还建议您不要在 application.js 中编写您的 JS,而仅将此文件用作清单文件,其中包含您通过 Rails 的其他脚本 资产管道.

I'd also advice you not to write your JS in application.js and use this file only as a manifest file, which includes your other scripts through Rails asset pipeline.

您也可以利用 javascript 助手 javascript_tag 在您的 html.erb 文件中

Also you can take advantage of the javascript helper javascript_tag in your html.erb file

<%= javascript_tag "displayClock()" %>

这篇关于如何从 html.erb 调用 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆