Javascript html 元素包装函数中的事件

Javascript event in a wrapper function for a html element

我有以下问题: 假设在我的 html 页面中我有以下元素:

<button onclick="myfunction(id)">Save</button>

在我的 javascript 文件中

(function(){

   function myfunction(id){
     // magic happends
   };

})();

在这种情况下,它不会工作,因为 myfunction 包含在 iife 函数中,所以我的问题是:是否有最佳实践可以保持 JavaScript 逻辑在包装函数中,同时可以访问 HTML 元素 ?

Is there a best practice in which you can keep your JavaScript logic inside a wrapper function and in the same time to be accessible to the HTML elments ?

根据您应用的结构,最好的方法是不使用内联事件处理程序,而是使用 DOM API 绑定处理程序:

(function(){

   function myfunction(id){
     // magic happends
   };

   button.addEventListener('click', myfunction);
})();

More information about event handling.

如果这不可能,并且您确实需要使用内联事件处理程序,您始终可以将函数设为全局:

(function(){

   window.myfunction = function myfunction(id){
     // magic happends
   };

})();