Rails 5 应用程序不会从 assets/javascripts 文件夹加载 JS [英] Rails 5 app won't load JS from assets/javascripts folder

查看:40
本文介绍了Rails 5 应用程序不会从 assets/javascripts 文件夹加载 JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,如果 /= require_tree 存在于 application.js 文件中,则会加载 assets/javascripts 文件夹中的任何 js 文件.但是,我无法让我的 JS 代码工作.我已经把它放在 assets/javascripts/locations.js 中,但它不起作用.另一方面,当我将它放在 application.html.erb 文件中的 script 标记中时,它运行得很好.任何想法我可能会错过什么?运行 Rails 5.2.JS代码如下.

As I understand it any js file in the assets/javascripts folder is loaded if /= require_tree is present in the application.js file. I can't get my JS code to work, however. I have put it in assets/javascripts/locations.js and it doesn't work. When I put it in a script tag in my application.html.erb file it worked perfectly on the other hand. Any ideas what I could be missing? Running Rails 5.2. The JS code is below.

locations.js

locations.js

var locations = ["coordinatesStore"]
  .map(id => document.getElementById(id));

Array.prototype.forEach.call(
  document.querySelectorAll('.add-button'),
  (button, i) => {
    button.addEventListener('click', () => getLocation(i));
  }
);

function getLocation(i) {
  var location = locations[i];
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => {
      location.value = latitude + ", " + longitude;
    });
  } else { 
    location.value = "Geolocation is not supported by this browser.";
  }
}

我的 application.html.erb 中有这个标签

I have this tag in my application.html.erb

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

推荐答案

在哪里<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>在您的 application.html.erb 中?

Where is <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> in your application.html.erb ?

尝试将它放在 body 标签的末尾,至少在 <%= yield %>

Try putting it at the end of your body tag, at least after the <%= yield %>

这篇关于Rails 5 应用程序不会从 assets/javascripts 文件夹加载 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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