Rails Asset Pipeline 未加载我的 javascript 文件(为什么此代码不起作用) [英] Rails Asset Pipeline is not loading my javascript file (why won't this code work

查看:16
本文介绍了Rails Asset Pipeline 未加载我的 javascript 文件(为什么此代码不起作用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将它包含在视图本身中,则此代码有效,如果我将其直接包含在 Application.js 文件中,则此代码有效,但如果我将其包含在 assets/javascripts/mailers.js 文件中,则它将不起作用.. 谁能告诉我我做错了什么,谢谢.

This code works if I include it in the view itself and it works if I include it directly into the Application.js file, but it will not work if I include it in the assets/javascripts/mailers.js file... can anyone tell me what i am doing wrong, thanks.

function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus();}};

也许我叫错了?这是视图中的代码:

Maybe I am calling it incorrectly? Here's the code in the view:

<%= text_field_tag :search_mailer, nil, autofocus: true, onkeyup: "myFunction(this.value)" %>

我还需要在上面包含的 mailers.js 文件中添加任何其他内容吗?因为这就是该文件中的全部内容.mailers.js 文件中唯一的代码是:

is there anything else i have to add into the mailers.js file I included above? Because that is all that is in that file. The only code in mailers.js file is:

function myFunction(val) {
if (val.length == 10) {
document.getElementById('search_button').focus();}};

推荐答案

您可能没有将文件包含在清单文件中.清单文件将 assets/javascripts 目录中的所有 .js 文件预编译为一个大文件.这是在您的应用程序上运行的文件.如果您的 .js 文件不在那里,则它不会被包含在内,这就是为什么什么都不会发生.

You have probably missed including the file in your manifest file. The manifest file precompiles all the .js files in the assets/javascripts directory into one large file. This is the file that is running on your application. If you do not your .js file there, it is not included and that's why nothing happens.

包含文件的正确方法是:

The right way to include your files is:

//= require mailers.js

在您的 application.js 文件中.更重要的是,默认情况下你有

in your application.js file. What's more, by default you have

//= require_tree .

需要来自 assets/javascript 路径的所有 js 文件.

which requires all js files from assets/javascript path.

如果您想专门为视图包含它,请将其放入:

<%= javascript_include_tag "mailers", "data-turbolinks-track" => true  %>

为此,如果预编译为false,则必须单独添加文件:在 config/initializers/assets.rb

For this, if precompilation is false, you have to add the file separately: In config/initializers/assets.rb

 Rails.application.config.assets.precompile += %w( mailers.js )

在 config/application.rb

config.assets.precompile += %w( mailers.js )

如果您有同名的 .js 和 .coffeescript 文件,问题也可能是应用程序预编译了错误的文件.你可以试试跑

The issue might be also that the application precompiles the wrong file if you have a .js and .coffeescript file with the same name. You can try running

   rake assets:clean
   rake assets:precompile

然后再次运行服务器.

这篇关于Rails Asset Pipeline 未加载我的 javascript 文件(为什么此代码不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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