Undefined method with coffescript using html event

2019-08-28 23:16发布

I have this line of code in my html

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

And My Coffescript

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

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

2条回答
男人必须洒脱
2楼-- · 2019-08-29 00:11

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).


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

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.


Try changing your Coffeescript to:

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

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

查看更多
▲ chillily
3楼-- · 2019-08-29 00:16
@editfunction = editfunction = (id) ->
    console.log 'Yeheyyy'

this will works :)

查看更多
登录 后发表回答