Ruby on Rails 4:如何在Rails Web应用程序中包含Javascript文件?

我正在构建一个Rails 4 Web应用程序,我想在我的应用程序中包含一些.js文件。 是否可以直接将JavaScript文件添加到我的Rails ..app/assets/javascripts文件夹中,并在application.js中添加这样的引用?

 //= customejsfile.js 

这是正确的方法吗? 如果是的话,我是否可以按照添加jQuery和Bootstrap库的相同步骤进行操作?

任何帮助表示赞赏。

包含文件的正确方法是:

 //= require customejsfile 

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

 //= require_tree . 

这需要来自assets/javascript路径的所有js文件,所以你不必自己输入(你不应该,或者你的文件包括两次)。 默认情况下包含JQuery库(它来自jQuery gem)。 如果你想要Bootstrap,那么你可以这样做或者使用现有的gem之一,比如bootstrap-generators或twitter-bootstrap-rails 。

看一下application.html.erb文件,您将看到application.js是通过以下方式引用的:

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

所以,当我遇到这个挑战时,我所做的是:在我想引用我的自定义javascript的文件中添加此脚本,但这次mi修改了参数。 所以,而不是“应用程序”,我有这个:

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

希望这可以帮助。

您必须在application.js中显式添加jquery和bootstrap,而您将自动包含需要目录树的自定义文件。 如果你看看你的application.js应该有一个清单说。 这就是你的application.js在bootstrap和jquery中应该是这样的

 // 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 vendor/assets/javascripts of plugins, if any, 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/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require bootstrap //= require bootstrap/affix //= require bootstrap/alert //= require bootstrap/button //= require bootstrap/carousel //= require bootstrap/collapse //= require bootstrap/dropdown //= require bootstrap/tab //= require bootstrap/transition //= require bootstrap/scrollspy //= require bootstrap/modal //= require bootstrap/tooltip //= require bootstrap/popover //= require turbolinks //= require_tree . 

无需在此列表中添加自定义文件,因为您需要使用last指令( require tree . )处于application.js(或目录树中较低位置)的同一级别的所有文件require tree .