单击事件上的 CoffeeScript 不起作用

CoffeeScript on click event not working

我是 CoffeeScript 和 JS 的新手。我正在尝试在单击 div 时创建警报,但我不确定为什么我的代码无法正常工作。所有这些文件都在同一目录中。

first.coffee

$('#button').on 'click', -> alert 'Hello World!'

我在 button.

之前尝试过使用和不使用哈希

编译后:

first.js

// Generated by CoffeeScript 1.12.4
(function() {
  $('#button').on('click', function() {
    return alert('Hello World!');
  });

}).call(this);

HTML 看起来像这样。我也试过将脚本移动到页眉,但我认为这没有什么不同。

first.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>CoffeeScript</title>
        <link rel="stylesheet" type="text/css" href="first.css">
    </head>
    <body>
        <div id='button'></div>
        <script src='first.js'></script>
    </body>
</html>

以及 div 的样式:

first.css

#button {
    width: 100px;
    height: 100px;
    background-color: black;
}

您需要在脚本之前添加对 jQuery javascript 库的引用

<body>
    <div id='button'></div>
    <script src='/path/to/jquery-3.1.1.min.js'></script>
    <script src='first.js'></script>
</body>

您需要将 jQuery 下载到您的系统并提供正确的路径。