2013-05-17 22 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上添加它,它們會重複。