简体   繁体   English

如何将已编译的coffescript放入我的html页面

[英]How to put the compiled coffescript in my html page

I'm new to coffeescript and javascript I wrote a simple code => 我是coffeescript和javascript的新手,我写了一个简单的代码=>

 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 " 我将生成的javascript放入html,通过单击按钮调用coffee函数,但它没有显示警报窗口,Firebug告诉我“ReferenceError:coffee 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. 但由于您已经在使用jQuery,因此更好的解决方案是将click处理程序附加到DOM元素。

number = 42

$('input').click ->
   ans = confirm "Ready?"
   "your answer is #{ans}"

Finally, returning a String from onClick seems not so useful. 最后,从onClick返回一个字符串似乎没那么有用。 Maybe alert ? 也许alert

You're defining the coffee function as a local variable to another function, so it won't be available in the global scope. 您将coffee函数定义为另一个函数的局部变量,因此它不会在全局范围内可用。

It's not recommended to put the onclick events to elements in HTML anyway, so attaching the event with jQuery should fix the problem: 不建议将onclick事件放到HTML中的元素中,因此使用jQuery附加事件应该可以解决问题:

number = 42
coffee = ->
    ans = confirm "Ready?"
    "your answer is #{ans}"

$("input[name=lala]").on "click", coffee

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM