在IE9的html页面中访问js内部的全局函数(Accessing global function inside js in html page on IE9)

编程入门 行业动态 更新时间:2024-10-27 17:10:59
在IE9的html页面中访问js内部的全局函数(Accessing global function inside js in html page on IE9)

我试图访问我在我的main.js文件中声明的全局函数,并尝试在html页面中使用它:

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

和我的main.js文件

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

这适用于所有浏览器,但IE9并未测试其他IE版本。 你觉得我做错了什么? 或者它与IE有关?

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:

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

And my main.js file

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

This works on all browsers but IE9 and haven't tested other IE versions. What do you think I'm doing wrong? or is it something that has to do with IE?

最满意答案

你应该在你的main.js中像这样传递窗口对象

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

“()”中的function关键字后面的变量是函数内部传递的参数的别名,而封装函数末尾的“()”内的变量是要传递的实际变量。

DEMO: http : //codepen.io/anon/pen/aOgZdB - 已经在IE中试用过了。

另一件事,我认为你可以直接将函数绑定到窗口,而不需要将它放在封装的函数中,如:

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

在你的main.js中没有封装它。

you should pass window object like this in your main.js

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

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.

更多推荐

本文发布于:2023-08-03 00:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382438.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   函数   页面   js   html

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!