将 javascript 代码添加到 rails 应用中

Add javascript code into the rails app

实际上,我无法将 javascript 代码添加到我的 rails 应用程序中。

我也试过把 import.js 放在 "app/assets/javascripts" 里,但也没用。

我还添加了,//= 需要在 application.js 文件末尾导入,但仍然没有 working.As 结果整个应用程序卡住了。

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();
        });
    });

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 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 文件中需要有一个 //= require_tree .。这样做是自动需要 javascripts 目录中的所有文件。

接下来,(我不完全确定这是最佳实践)我在 html.erb 文件中调用 javascript 的方式在 <script> 标签内。我将在下面举一个我的代码示例。我只是 最近 弄清楚了如何在 rails 中从 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>

所以我实际上把它放在了一个脚本标签中,就像你看到的那样。希望这有帮助。