[英]CoffeeScript - How to work with coffeescript in ruby on rails?
I am working with CoffeeScript in Ruby on rails. 我正在使用Rails中的Ruby中的CoffeeScript。 And I am using http://js2.coffee/ to convert my javascript and jquery into CoffeeScript. 我正在使用http://js2.coffee/将JavaScript和jquery转换为CoffeeScript。
We know, Ruby on Rails provides us by default .coffee files when we create any controller. 我们知道,Ruby on Rails在创建任何控制器时都会默认为我们提供.coffee文件。
In my view folder, I have defined a test.html.erb
file, I have a button 在我的视图文件夹中,我定义了一个test.html.erb
文件,我有一个按钮
<button id="p">try</button>
and if I define the script for this button by using javascript or jquery in the same page ie test.html.erb
it works. 并且如果我通过在同一页面(即test.html.erb
使用javascript或jquery来为此按钮定义脚本,则它可以工作。
My javascript code 我的JavaScript代码
document.getElementById("p").onclick = function() {myFunction()};
function myFunction() {
alert("hello");
}
and my jquery 和我的jQuery
$(document).ready(function(){
$("#p").click(function(){
alert("hello");
});
});
And now I have created a custom file in app/assets/javascripts/test.coffee
现在我已经在app/assets/javascripts/test.coffee
创建了一个自定义文件
coffeescript of my jquery code 我的jquery代码的coffeescript
$(document).ready ->
$('#p').click ->
alert 'hello'
return
return
and when I use this in my test.coffee it works fine. 当我在test.coffee中使用它时,效果很好。
coffeescript of javascript code javascript代码的脚本
myFunction = ->
alert 'hello'
return
document.getElementById('p').onclick = ->
myFunction()
return
and when I use this code in my test.coffee it shows error in my console 当我在test.coffee中使用此代码时,它在控制台中显示错误
Uncaught TypeError: Cannot set property 'onclick' of null
I have also try the test.js.coffee
but still get the same error 我也尝试过test.js.coffee
但仍然遇到相同的错误
so should I only use the coffeescript generated by jquery or is there any way to use the coffeescript generated by javascript? 所以我应该只使用jquery生成的coffeescript还是有什么方法可以使用javascript生成的coffeescript?
The problem is element_with_id "p" is not found on the page because coffeescript is being load before the page load. 问题是在页面上找不到element_with_id“ p”,因为在页面加载之前正在加载coffeescript。 Wrap your code inside document.ready
this will call the coffeescript once the page is completed loaded. 将您的代码包装在document.ready
,一旦页面加载完成,这将调用coffeescript。
$(document).ready ->
myFunction = ->
alert 'hello'
return
document.getElementById('p').onclick = ->
myFunction()
return
在文档准备就绪后调用第一个方法,但是在第一个方法之前调用第一个方法,此时可能尚未创建ID为'p'的元素,因此document.getElementById('p')
返回null,并提出上述错误。
We can add java-script using back-tick(`) in coffee-scripts. 我们可以在咖啡脚本中使用back-tick(`)添加Java脚本。
window.onload = ->
`document.getElementById("demo").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.