2016-03-24 17 views
0

実際には、私のレールアプリケーションにJavaScriptコードを追加する際に問題があります。javascriptコードをレールアプリケーションに追加

「app/assets/javascripts」にimport.jsを入れてみましたが、どちらもうまくいきませんでした。

また、// application.jsファイルの最後にインポートが必要ですが、まだ動作していません。その結果、アプリケーション全体が突っ込まれました。

index.html.erb

<a href="#">TEST</a> 

<div id = "test"> 

    <h2>Import Statements</h2> 

    <%= form_tag import_samples_path, multipart: true do %> 
    <%= file_field_tag :file %> 
    <%= submit_tag "Import" %> 
    <% end %> 

</div> 

sample.coffee

# Place all the behaviors and hooks related to the matching controller here. 
# All this logic will automatically be available in application.js. 
# You can use CoffeeScript in this file: http://coffeescript.org/ 

    $(document).ready(function() { 
     $("div#test").hide(); 
     $("a").click(function(event) { 
      event.preventDefault(); 
      $("div#test").toggle(); 
     }); 
    }); 

は、事前に

// 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 any plugin's vendor/assets/javascripts directory 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/rails/sprockets#sprockets-directives) for details 
// about supported directives. 
// 
//= require jquery 
//= require jquery_ujs 
//= require turbolinks 
//= require bootstrap-sprockets 
//= require nicetitle 

感謝をapplication.js。

答えて

0

ここでは物事のカップル:

まず第一に - あなたのapplication.jsファイルの//= require_tree .内部を持っている必要があります。これは自動的にあなたのjavascriptsディレクトリ内のすべてのファイルを必要とします。私はhtml.erbファイルの内部でJavaScriptを呼び出す

次に、(私はこれがベストプラクティスであることを完全にわからないんだけど)の方法は、<script>タグの内側にあります。以下に私のコードの例を載せます。私だけ非常に最近は、レールの中でhtmlの内部からJSを呼び出す方法を考え出したので、これはおそらくベストプラクティスではないと言われましたが、これは私がやった方法です。

<script language="javascript" type="text/javascript"> 
     var counts = ['Count'] 
     var dates = ['x'] 
     <% @chart.datasource.datapoints.each do |c| %> 
      dates.push("<%= c.date %>") 
      counts.push(<%= c.count %>) 
     <% end %> 
     chart(counts, dates); 
</script> 

実際、あなたが見たようなスクリプトタグの中に入れています。うまくいけば、これは役に立ちます。

+0

ありがとうございました。はい、それは働いています。ほとんどのビューでapplication.html.erbで使用したいのですが? –

関連する問題