2013-05-17 23 views
2

我应该首先提到我没有预编译。Ruby on Rails HTML中包含的JS文件的副本

我有8个不同的.js文件(7,不计的application.js),当我使用<%= javascript_include_tag 'application' %>它打印出:

<script src="/assets/admin.js?body=1" type="text/javascript"></script> 
<script src="/assets/brand.js?body=1" type="text/javascript"></script> 
<script src="/assets/category.js?body=1" type="text/javascript"></script> 
<script src="/assets/home.js?body=1" type="text/javascript"></script> 
<script src="/assets/product.js?body=1" type="text/javascript"></script> 
<script src="/assets/setting.js?body=1" type="text/javascript"></script> 
<script src="/assets/user.js?body=1" type="text/javascript"></script> 
<script src="/assets/application.js?body=1" type="text/javascript"></script> 

正因为如此,一些我的jQuery(使用切换)不工作因为他们正在执行多次。

我该如何才能简单地使用application.js?

我的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 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 
// the compiled file. 
// 
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD 
// GO AFTER THE REQUIRES BELOW. 
// 
//= require jquery 
//= require jquery_ujs 
//= require jquery.ui.all 
//= require_tree . 
+0

你的'application.js'文件是什么样的? '应用。js'实际上应该是包含所有其他文件的清单。也许我错过了一些东西,并没有完全理解你的问题。哪些文件被复制? – theIV

+0

所有Js文件都合并到application.js中,这意味着它们不再需要在HTML中进行链接。因为它们是,代码被复制到独立的JS文件和application.js文件中。我用我的application.js清单更新了我的问题 –

回答

3

除了像Mike说的那样删除//= require_tree .。试试下面的命令:

$ rake tmp:clear tmp:create assets:clean 

这将清除临时文件&缓存的资源文件。

此外,如果您只需要单个application.js而不是7个.js包含脚本标记。设置下列选项config/environments/development.rb

# Expands the lines which load the assets 
    config.assets.debug = false 

希望它可以帮助

+0

'config.assets.debug = false'是我想要的,现在我只有两个文件(.js和.css)。谢谢。 –

+0

不客气:) – CuriousMind

0

//= require_tree .负载一切都在同一目录清单(.)。

如果您想手动添加JavaScript,只需删除该行即可。但是,如果您在每个页面上都包含所有JavaScript,请将该行保留在那里并删除您的包含。

0

您的问题是,application.js中加载所有的JS文件在当前目录中,因为该行的“// = require_tree。”并且可能你在不同的页面中为你的html元素使用了相同的名称(id和class),所以一种解决方案是继续使用“// = require_tree”。在你的application.js中,为你的页面中的每个元素赋予唯一的名称,另一种解决方案是删除“// = require_tree”。从您的application.js和使用:

<%= javascript_include_tag "application", controller_name %> 

这里的时候,您生成一个新的控制器,轨道会自动为你创建与控制器的名称的JavaScript文件,当您添加的javascript_include_tag“CONTROLLER_NAME”选项,我们将添加当前控制器的js文件,最后将您的javascript指令放置在这些文件切换控制器中,然后放在这里。

我觉得这个方法很好柠但也有其他的解决方案,你可以在这里找到这个问题的一些其他答案:

Rails 3.1 asset pipeline: how to load controller-specific scripts?

好运;)

0

我有同样的问题。检查您是否未在application.html.erb上添加其他js文件。因为如果你有//= require_tree。在application.js中它会添加所有内容,所以如果你在application.html.erb上添加它,它们会重复。