【问题标题】:use javascript in rails 3.2 without coffeescript在没有咖啡脚本的 Rails 3.2 中使用 javascript
【发布时间】:2013-01-17 11:48:18
【问题描述】:

我使用的是 Rails 3.2,它是为咖啡脚本设置的。我知道 Coffeescript 是一门很棒的语言,而且学习起来并不难,但我刚刚开始关注 Javascript 和 jQuery。所以我的问题是:有没有一种简单的方法可以将 rails 3.2 设置为使用 Javascript? 目前,我的 jQuery 在我的视图中位于 <script></script> 标记中 (timeline/index.html.erb)。我想把它移到一个 .js 文件中。我尝试将我的timeline.js.coffee 的名称更改为只是timeline.js 并将jQuery 放在那里,但我得到Uncaught SyntaxError: Unexpected token ILLEGAL。

除了“学习coffeescript”这个显而易见的答案,我应该怎么做?

【问题讨论】:

    标签: javascript ruby-on-rails-3 coffeescript


    【解决方案1】:

    清单文件和指令
    http://guides.rubyonrails.org/asset_pipeline.html#manifest-files-and-directives

    在app/assets/javascripts中添加js文件,然后在application.js中添加文件


    你的 js 文件

    alert("here");
    

    应用程序.js

    //= require_tree .
    or
    //= require your_js_file_name
    

    然后,它将从您的app/views/layouts/application.html.erb 中的以下代码中获取

    <%= javascript_include_tag "application" %>
    

    【讨论】:

    • 默认情况下都是这样设置的。除了默认文件是.js.coffee,我尝试将其更改为.js
    【解决方案2】:

    我在正确的轨道上。要在 rails 3.2 中切换到 javascript,您只需删除 .coffee 扩展名。但是,您还需要确保对 cme​​ts 使用 // 而不是 #

    //# 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://jashkenas.github.com/coffee-script/
    

    【讨论】:

      【解决方案3】:
      $ rails -v
      Rails 3.2.11
      

      这个怎么样?
      http://bit.ly/VHEnBX

      git clone it
      cd js_test
      bundle
      rails s -d
      open http://localhost:3000
      
      # stop the detached server 
      kill -9 `cat tmp/pids/server.pid`
      

      您应该会看到来自浏览器的here 警报。

      这只是一个简单的 js 文件。没有 .coffee 扩展名或任何扩展名。 http://bit.ly/UPe2mp

      【讨论】:

        【解决方案4】:

        您可以在 Gemfile 中简单地注释掉 gem 'coffee-rails'

        【讨论】:

        • 它仍然应该将 .js 识别为带有或不带有咖啡导轨的 javascript。它的作用。
        猜你喜欢
        • 1970-01-01
        • 2011-11-08
        • 1970-01-01
        • 2012-05-19
        • 2013-06-19
        • 2016-06-27
        • 2014-02-04
        • 2015-01-02
        • 1970-01-01
        相关资源
        最近更新 更多