【发布时间】:2015-04-07 12:58:57
【问题描述】:
我尝试在我的 ruby 应用程序中添加 js 操作。 我阅读了 Rails 指南中的资产管道和使用 JavaScript,但我无法重现第二个中描述的内容。 我是 Rails 的初学者,所以也许我对文件做了太多的“操作”,还有扩展......
我有
控制器“mycontroller”app/controllers/mycontroller_controller.rb
class mycontrollerController < ApplicationController
def new
end
end
application.js 应用程序/资产/javascripts
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
mycontroller.coffee app/assets/javascripts
当我在浏览器中加载应用程序时,资产似乎已正确包含
<script src="/assets/mycontroller-d915d2e33a0815bf7b1ac3c478a90599.js?body=1" data-turbolinks-track="true"></script>
<script src="/assets/application-fdae31866ddfa65ac8bed4781fb60a9c.js?body=1" data-turbolinks-track="true"></script>
问题:我必须重命名 .js.coffee 中的 .coffee 文件吗?我试过了,但没有任何改变。
我遵循“在 Rails 中使用 JavaScript”并像这样修改了我的文件:
new.html.erb app/views/mycontroller
<a href="#" onclick="paintIt(this, '#990000')">Paint it red</a>
mycontroller.coffee app/assets/javascripts
paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
我认为咖啡脚本编译正确:
(function() {
var paintIt;
paintIt = function(element, backgroundColor, textColor) {
element.style.backgroundColor = backgroundColor;
if (textColor != null) {
return element.style.color = textColor;
}
};
}).call(this);
但是点击什么也没发生……有什么想法吗?
提前感谢我们的帮助。
【问题讨论】:
-
Google Chrome 的 Javascript 控制台中是否有与 javascript 相关的错误?而且,您的 Rails 应用程序在哪些环境(例如开发、测试或生产环境)上运行?
-
确实,我有这个错误:
Uncaught ReferenceError: paintIt is not defined onclick。否则,我的应用程序在本地服务器上运行,因此我认为是在开发环境中。谢谢。
标签: javascript ruby-on-rails ruby coffeescript