Undefined method with coffescript using html event onclick=“function()”

会有一股神秘感。 提交于 2019-12-11 14:33:15

问题


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


回答1:


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.




回答2:


@editfunction = editfunction = (id) ->
    console.log 'Yeheyyy'

this will works :)



来源:https://stackoverflow.com/questions/52088803/undefined-method-with-coffescript-using-html-event-onclick-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!