ES6 module “Uncaught ReferenceError: function is not defined at HTMLButtonElement.onclick”

前端 未结 1 1868
长发绾君心
长发绾君心 2021-01-18 00:32

I am trying ES6 module in google chrome. I would like to launch an alert() (in an imported function) when i click on the button.

js/notification.js is well loaded bu

相关标签:
1条回答
  • 2021-01-18 01:13

    Functions used in onxyz-attribute-style handlers must be globals (it's one of the many reasons not to use them). Your function isn't a global, it's local to the module in which you're importing it. (Remember: Your main script is a module too; if it weren't, you couldn't use import in it.)

    You could make it a global by assigning to a window property:

    window.createNotification = createNotification;
    

    but it would be much better to use modern event handling:

    document.querySelector("#container button").addEventListener("click", createNotification);
    

    Live example on plnkr, obviously will only work on cutting-edge browsers with module support.


    Side note: As Andreas points out, type="error" isn't valid for button elements. Valid types are button, submit, or reset, with submit being the default. (I've changed it to button in the plnkr.)

    0 讨论(0)
提交回复
热议问题