调用使用咖啡脚本定义的函数

Calling functions defined with coffee script?

本文关键字:定义 函数 脚本 咖啡 调用      更新时间:2023-09-26

我有以下咖啡脚本代码来生成和警报框:

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