I'm new to coffeescript and javascript I wrote a simple code =>
1 number = 42
2 coffee = ->
3 ans = confirm "Ready?"
4 "your answer is #{ans}"
And I put the generated javascript into html call the coffee function by clicking the button, but it didn't show the alert window,and Firebug told me "ReferenceError: coffee is not defined "
1 <head>
2 <script type=”text/javascript” src=”http://codeorigin.jquery.com/jquery-1.10.2.js"> </script>
3 <script type="text/javascript" >
4 // Generated by CoffeeScript 1.6.3
5 $(document).ready(
6 function(){
7
8 var coffee, fk, number;
9
10 number = 42;
11
12 coffee = function() {
13 var ans;
14 ans = confirm("Ready?");
15 return "your answer is " + ans;
16 };
17 });
18
19 </script>
20 </head>
21 <body>
22 <input type=button name="lala" value="hihi" onclick="coffee();">
23 </body>
You need to export the parts of your script that you want visible to the outside world.
Easiest way would be to do
window.myCoffee = {}
number = 42
myCoffee.coffee = ->
ans = confirm "Ready?"
"your answer is #{ans}"
That is because the script is wrapped into its own private scope.
But since you are already using jQuery, a better solution would be to attach the click handler to the DOM element.
number = 42
$('input').click ->
ans = confirm "Ready?"
"your answer is #{ans}"
Finally, returning a String from onClick seems not so useful. Maybe alert
?
You're defining the coffee
function as a local variable to another function, so it won't be available in the global scope.
It's not recommended to put the onclick events to elements in HTML anyway, so attaching the event with jQuery should fix the problem:
number = 42
coffee = ->
ans = confirm "Ready?"
"your answer is #{ans}"
$("input[name=lala]").on "click", coffee
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.