2017-03-16 82 views
0

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

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; 
} 

回答

0

您需要添加一个引用了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下载到您的系统并提供正确的路径。

+0

谢谢,这解决了它! –