coffee脚本没有'在我的ruby应用程序中不起作用
coffee scripts doesn't work in my ruby app
我试图在我的ruby应用程序中添加js操作。我读了资产管道&在Rails指南中使用JavaScript,但我无法重现第二个指南中描述的内容。我是rails的初学者,所以也许我对文件做了太多的"操作",还有扩展。。。
我有
控制器"mycontroller"app/controllers/mycontroller_controller.rb
class mycontrollerController < ApplicationController
def new
end
end
application.js app/assets/javascripts
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
mycontroller.coffee应用程序/资产/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应用程序/资产/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);
但点击不会发生任何事情。。。知道吗?
提前感谢我们的帮助。
问题是CoffeeScripts旨在以"不引人注目的方式"与DOM通信,这样您就不会在HTML中看到任何JS的迹象。发生这种情况的原因是,您的脚本被编译为自执行匿名函数,该函数将其作用域与全局命名空间隔离。paintIt
不会"泄漏"到外部。这是经过设计的(这里有一些解释)。你需要采取不同的做法。
为了区分属性的用途,我个人将任何与行为相关的东西放在data-*
属性中,并将事件绑定到像[data-paint]
这样的选择器上,以指示此类属性的存在。我建议你这样重写HTML:
<a href="#" data-paint="#990000">Paint it red</a>
然后为每个data-paint
:处理click
事件
$("[data-paint]").on "click", ->
# `@` is basically `this` and `@thing` is `this.thing`
# `@dataset` contains the data attributes of the given element
@style.color = @dataset.paint
你完了。请参阅JSFiddle。
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 可以't让我的if语句处理js中的html表单输入
- 我的单元测试选项是什么
- 为什么不't我的ruby代码与javascript文件一起插入
- coffee脚本没有'在我的ruby应用程序中不起作用
- 我的Ruby在轨道上删除功能不起作用
- Heroku 它的调用 JavaScript 代码不在我的 Ruby on Rails 项目中
- Ruby on Rails - 我的“checkall”复选框功能跳转到数据表上的页面
- 如何调试我的代码Ruby,Javascript,CSS
- 为什么在视图中解析时,我的嵌入式ruby json字符串用html实体编码
- 在我启动我的selenium脚本之前,如何在浏览器的localStorage中使用ruby设置item
- Bootstrap模式并没有留在我的ruby on rails项目中
- Ruby on Rails:为什么我的delete链接不起作用?
- 我如何通过Ajax提交表单数据到我的Ruby控制器
- 重写我的应用程序从ruby/rails到javascript/express.mongodb适合我的需要吗?
- 在我的ruby控制器函数中刷新网页
- ruby on rails-如何在HTML网页中包含我的Javascript文件和/或jQuery
- ruby on rails-将我的文件重命名为.js.erb可以在javascript中编写erb,但不能在erb中编写
- Ruby on Rails得到谷歌分析访问者计数和保存到我的应用程序数据库
- 如何在不轮询的情况下从Ruby REST/CUD API不断更新我的ReactJS客户端