简体   繁体   English

我可以在CoffeeScript文件中使用普通的JavaScript吗?

[英]Can I use ordinary JavaScript in CoffeeScript file?

I am trying to add some JavaScript code in my Ruby on Rails application. 我想在Ruby on Rails应用程序中添加一些JavaScript代码。 I have already created for me, some js.coffee files for each view in my assets. 我已经为我创建了一些js.coffee文件,用于我的资产中的每个视图。 Since, I am not familiar with the CoffeeScript I just passe some ordinary JavaScript/jQuery line in the file, such as: 因为,我不熟悉CoffeeScript,我只是在文件中传递一些普通的JavaScript / jQuery行,例如:

if ($('#cart').length == 1) { $('#cart').hide("blind", {direction: "vertical" }, 1000); }

$('#cart tr').not('.total_line').remove();

but the following error was thrown: 但抛出以下错误:

Error: Parse error on line 1: Unexpected 'POST_IF' (in /home/gotqn/Aptana Projects/depot/app/assets/javascripts/carts.js.coffee) 错误:第1行的解析错误:意外的'POST_IF'(在/ home / gotqn / Aptana Projects / depot / app / assets / javascripts / carts.js.coffee中)

The source is pointed on 指出了来源

Showing /home/gotqn/Aptana Projects/depot/app/views/layouts/application.html.erb where line #6 raised: 显示/ home / gotqn / Aptana Projects / depot / app / views / layouts / application.html.erb第6行引出:

and in this file on line #6 I got: 在第6行的这个文件中我得到了:

<%= javascript_include_tag "application" %>

I am new in Ruby on Rails, but what I suppose is happening is that I am not able to write simple JavaScript in the CoffeeScript. 我是Ruby on Rails的新手,但我想要发生的事情是我无法在CoffeeScript中编写简单的JavaScript。 If this is true, can I only remove the .coffe extension and be sure that the Rails magic will work and load the file? 如果这是真的,我是否只能删除.coffe扩展名并确保Rails魔法可以正常工作并加载文件?

From the docs on coffeescript.org : 来自coffeescript.org上的文档:

Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through. 希望您永远不需要使用它,但如果您需要在CoffeeScript中散布JavaScript代码片段,则可以使用反引号直接传递它。

So yes, you can use JavaScript in CoffeeScript - just surround it in backticks : 所以,是的,您可以在CoffeeScript中使用JavaScript - 只需将其包围在反引号中

`function greet(name) {
return "Hello "+name;
}`

# Back to CoffeeScript
greet "Coffee"
# => "Hello Coffee"

hello = `function (name) {
return "Hello "+name
}`
hello "Coffee"
# => "Hello Coffee"

It's highly advisable that you just convert your code to CoffeeScript instead, though. 不过,您最好将代码转换为CoffeeScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM