简体   繁体   English

在IE9上的html页面中访问js内的全局函数

[英]Accessing global function inside js in html page on IE9

I'm trying to access a global function that I declare inside my main.js file and try to use it in the html page: 我正在尝试访问我在main.js文件中声明的全局函数,并尝试在html页面中使用它:

<!DOCTYPE html>
<html>
  <head>

  </head>
  <body>
    <script src='main.js'></script>
    <script>
    (function(){
      window.myFunction();
    })();
    </script>
  </body>
</html>

And my main.js file 还有我的main.js文件

(function(){
  window.myFunction = function(){
    alert(1);
  }
})();

This works on all browsers but IE9 and haven't tested other IE versions. 这适用于所有浏览器,但IE9并没有测试其他IE版本。 What do you think I'm doing wrong? 你觉得我做错了什么? or is it something that has to do with IE? 或者它与IE有什么关系?

you should pass window object like this in your main.js 你应该在main.js中传递这样的window对象

(function(w){
  w.myFunction = function(){
    alert(1);
  }
})(window);

the variables after function keyword inside "()" is the alias of the passed parameter inside the function, while the variables inside "()" on the end of encapsulated function is the real variables being passed. “()”中的函数关键字后面的变量是函数内部传递参数的别名,而封装函数末尾的“()”内的变量是传递的实变量。

DEMO : http://codepen.io/anon/pen/aOgZdB - already tried in IE. 演示: http//codepen.io/anon/pen/aOgZdB - 已在IE中尝试过。

Another thing I think you can bind function to window directly, and you don't need to put it inside encapsulated function like: 我认为你可以直接将函数绑定到窗口的另一件事,你不需要把它放在封装函数中,如:

   window.myFunction=function(){
      alert(1);
   }

in your main.js without encapsulating it. 在你的main.js中没有封装它。

Try this: 尝试这个:

<!DOCTYPE html>
<html>
  <head>
  </head>
    <body>
      <script src='main.js'></script>
      <script>
        window.myFunction();
      </script>
    </body>
</html>

I don't have IE 9, so I don't know it works or not. 我没有IE 9,所以我不知道它是否有效。 But tested in IE 11. 但在IE 11中测试过。

(function(window){
  window.myFunction = function(){
    alert(1);
  }
})(window);

(function(){
     window.myFunction();
})();

http://jsfiddle.net/aqsrpkpm/ http://jsfiddle.net/aqsrpkpm/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM