如何知道来自不同...的变量..."名称空间&quot ;? [英] How to know variables from different..."namespaces"?

查看:156
本文介绍了如何知道来自不同...的变量..."名称空间&quot ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在外部javascript文件中访问另一个地方声明的变量?



假设在一个html文件中我有以下内容:

 < head> 
< script>
var a ='something';
< / script>
< head>
< body>
< iframe src =otherfile.html/>
< / body>

以及其他文件.html中的部分内容,我有

  alert(a); 

如何确保我收到一条提示消息something?

我认为Google Adsense会这样做,他们的代码是:

 < script type = text / javascript><! -  
google_ad_client =youdontneedtoknowthis;
google_ad_slot =5404192644;
google_ad_width = 728;
google_ad_height = 90;
// - >
< / script>
< script type =text / javascript
src =http://pagead2.googlesyndication.com/pagead/show_ads.js>
< / script>

脚本如何在 http://pagead2.googlesyndication.com/pagead/show_ads.js 知道这些变量(例如google_ad_client)?

解决方案

当一个变量没有定义 var 时,它被认为存在于全局范围中。当你的JS加载到你的页面时,它意识到当时全局存在的任何变量。所以,谷歌正在做的是定义一些变量,然后加载到外部脚本。


How can I reach some variable declared in another place from within an external javascript file ?

Suppose in an html file I have the following

<head>
 <script>
   var a = 'something';
 </script>
<head>
<body>
<iframe src="otherfile.html"/>
</body>

and inside otherfile.html, in the section, I have

alert(a);

How can I make sure I get an alert message saying "something" ?

I think Google Adsense does this, their code is:

<script type="text/javascript"><!--
google_ad_client = "youdontneedtoknowthis";
google_ad_slot = "5404192644";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

How can the script in http://pagead2.googlesyndication.com/pagead/show_ads.js know those variables (e.g. google_ad_client) ?

解决方案

when a variable is defined without var it is said to exist in global scope. When your JS is loaded into your page, it is aware of any variables that exist globally at that time. So, what google is doing is defining some variables and then loading in an external script.

这篇关于如何知道来自不同...的变量...&quot;名称空间&quot ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆