2017-03-16 356 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

謝謝,這解決了它! –