[英]Rails doesn't see simple Coffeescript
I am following http://guides.rubyonrails.org/working_with_javascript_in_rails.html tutorial about jquery - I am trying to run the simplest thing suck as: 我正在遵循有关jquery的http://guides.rubyonrails.org/working_with_javascript_in_rails.html教程-我正在尝试将最简单的东西作为运行:
welcome.js.coffee welcome.js.coffee
paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
and welcome index 和欢迎指数
<a href="#" onclick="paintIt(this, '#990000')">Paint it red</a>
this doesn't work too 这也行不通
<a href="#" onclick="paintIt(this, '#009900', '#FFFFFF')">Paint it green</a>
When I click it then color isn't changed. 当我单击它时,颜色不变。 What I am doing wrong or what I didn't do ?
我做错了还是没有做?
The best advice I can give is to firstly ensure the JS is being called, and then make it unobtrusive: 我能提供的最佳建议是,首先确保正在调用JS,然后使其不引人注目:
$("a").on "click", (e)->
e.preventDefault()
paintIt($(this), $(this).data("background"), $(this).data("foreground"))
<%= link_to "Paint It Red", "#", data: {background: '#990000', foreground: '#ffffff'} %>
<%= link_to "Paint It Green", "#", data: {background: '#009900', foreground: '#ffffff'} %>
Typically coffeescript output is wrapped in an anonymous function, so as not to pollute the global namespace. 通常,coffeescript输出包装在匿名函数中,以免污染全局名称空间。 Your javascript should look like this:
您的JavaScript看起来应该像这样:
(function() {
var paintIt;
paintIt = function(element, backgroundColor, textColor) {
element.style.backgroundColor = backgroundColor;
if (textColor != null) {
return element.style.color = textColor;
}
};
}).call(this);
So it should NOT be working - the paintIt
variable is inaccessible from onclick
attributes. 因此它不起作用-从
onclick
属性无法访问paintIt
变量。 You would need to expose it to the window
object for your example to work 您需要将其公开给
window
对象,以便您的示例起作用
paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
#expose as global
window.paintIt = paintIt
I believe that is just a first step though. 我相信那只是第一步。 Next would be to make the js unobstrusive and setup eventhandlers from within coffeescript.
接下来将是使js变得不干扰他人,并在coffeescript中设置事件处理程序。 And then there is no need to expose as a global.
然后就没有必要公开为一个整体。
paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
# use DOMContentLoaded or jQuery's: $(document).ready()
document.addEventListener('DOMContentLoaded', ->
#find <a> tags and setup event listeners
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.