调用使用咖啡脚本定义的函数
Calling functions defined with coffee script?
我有以下咖啡脚本代码来生成和警报框:
show_alert = () ->
alert("Hello! I am an alert box!")
编译为:
(function() {
var show_alert;
show_alert = function() {
return alert("Hello! I am an alert box!");
};
}).call(this);
在我的 html 中,我有以下内容
<input onclick='show_alert()' type='button' value='Show alert box' />
但是,没有显示警报框? 以下是从浏览器复制的 html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Test Rails Application</title>
<style type='text/css'>.application h1 {
color: lime; }
</style>
<script type='text/javascript'>(function() {
var show_alert;
show_alert = function() {
return alert("Hello! I am an alert box!");
};
}).call(this);
</script>
</head>
<body>
<h1>Hello from applicaiton.html.haml</h1>
<div class='application'><h1>Hello World</h1>
<input onclick='show_alert()' type='button' value='Show alert box' />
</div>
</body>
</html>
为什么我无法显示警报框?
你的问题是生成的javascript代码在另一个范围内。你必须解决这个问题通过将 -b
参数添加到 coffeescript 编译器或导出函数明确通过
root = exports ? this
root.show_alert = () -> alert("Hello! I am an alert box!")
有关导出和范围问题的详细信息,请查看 https://stackoverflow.com/a/4215132/832273
我用上面的咖啡脚本代码创建了一个工作 jsfiddle
我找到了两种解决此问题的方法首先在函数名称前添加 @
@say_hi = () ->
$(alert('Hello!!!'))
第二个在咖啡文件添加的末尾
window["say_hi"] = say_hi
在您的 coffeescrpt 代码中,尝试将函数保存到 window: window["show_alert"] = show_alert
相关文章:
- 用嵌套函数和默认函数定义函数
- 自定义函数中的光标位置
- Jquery未定义函数正在停止其他操作
- 在不破坏未定义函数的情况下,对多个视图使用单个js文件
- javascript无法重新定义函数内部的全局对象
- 定义函数时,如何捕获外部变量的当前值
- 能够在定义函数表达式之前使用它
- Google Sheet自定义函数返回0
- Javascript-defineProperty和直接在对象上定义函数之间的区别
- 其中是自定义函数中的属性
- 创建自定义函数以在函数上运行完整的多选下拉列表
- Google Sheets自定义函数条件格式
- 为什么当我需要位于顶部的函数时,在脚本中的某些点上没有定义函数
- 使用变量的名称,然后为该变量定义函数
- dalek回调或自定义函数
- 如何在angular ui模态控制器中定义函数
- Uncaught ReferenceError:尝试在Android网络视图中访问时未定义函数
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 在构造函数中定义函数会比将其附加到原型消耗更多的内存
- 使用 Javascript 中的函数重新定义函数