【发布时间】:2019-05-02 07:06:06
【问题描述】:
我正在使用 Ruby on rails 中的 CoffeeScript。我正在使用http://js2.coffee/ 将我的 javascript 和 jquery 转换为 CoffeeScript。
我们知道,当我们创建任何控制器时,Ruby on Rails 默认会为我们提供 .coffee 文件。
在我的视图文件夹中,我定义了一个test.html.erb 文件,我有一个按钮
<button id="p">try</button>
如果我在同一页面中使用 javascript 或 jquery 定义此按钮的脚本,即test.html.erb,它可以工作。
我的 JavaScript 代码
document.getElementById("p").onclick = function() {myFunction()};
function myFunction() {
alert("hello");
}
还有我的 jquery
$(document).ready(function(){
$("#p").click(function(){
alert("hello");
});
});
现在我在app/assets/javascripts/test.coffee 中创建了一个自定义文件
我的 jquery 代码的咖啡脚本
$(document).ready ->
$('#p').click ->
alert 'hello'
return
return
当我在我的 test.coffee 中使用它时,它工作正常。
javascript 代码的咖啡脚本
myFunction = ->
alert 'hello'
return
document.getElementById('p').onclick = ->
myFunction()
return
当我在 test.coffee 中使用此代码时,它会在我的控制台中显示错误
Uncaught TypeError: Cannot set property 'onclick' of null
我也尝试了test.js.coffee,但仍然遇到同样的错误
所以我应该只使用jquery生成的coffeescript还是有什么方法可以使用javascript生成的coffeescript?
【问题讨论】:
标签: javascript jquery ruby-on-rails coffeescript