使用html事件onclick =“" function()"的带有咖啡因的未定义方法; [英] Undefined method with coffescript using html event onclick="function()"

查看:176
本文介绍了使用html事件onclick =“" function()"的带有咖啡因的未定义方法;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的html中有这行代码

I have this line of code in my html

<a href="#" onclick="editfuntion(2)">






还有我的咖啡


And My Coffescript

editfunction = (id) ->
  console.log id
  return

为什么返回?
未被捕获的ReferenceError:HTMLAnchorElement.onclick上未定义editfunction

Why is it it returns ? Uncaught ReferenceError: editfunction is not defined at HTMLAnchorElement.onclick

推荐答案

Coffeescript将所有文件包装在立即执行的匿名函数。这意味着您定义的所有变量都在本地范围内,除非显式放置在全局名称空间中(在浏览器中是 window 对象,而在NodeJS中是 global )。

Coffeescript will wrap all files in an anonymous function which is immediately executed. This means all variables you define are locally scoped unless explicitly placed in the global namespace (in browsers it is the window object, while in NodeJS it's global).

来自 coffeescript.org (谈论在浏览器中使用Coffeescript,但也适用于使用编译为JS的Coffeescript):

From coffeescript.org (talking about using Coffeescript in a browser, but it also applies to using the Coffeescript compiled to JS ):

适用于CoffeeScript的常见警告-内联脚本将在闭包中运行,因此,如果要公开全局变量或函数,请将它们附加到window对象。

The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the window object.






尝试将Coffeescript更改为:


Try changing your Coffeescript to:

window.editfunction = (id) ->
  console.log id

这将在 window 对象,以便可以在 onclick 处理程序中使用。

This will expose the function globally on the window object so that it can be used within an onclick handler.

这篇关于使用html事件onclick =“&quot; function()&quot;的带有咖啡因的未定义方法;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆