简体   繁体   English

Javascript全局范围不起作用

[英]Javascript Global Scope not working

I'm trying to understand global scoping in js so that i can call a var from a different server into a webpage and access with js, but this simple test is not even working. 我试图了解js的全局作用域,以便可以从其他服务器调用var进入网页并使用js进行访问,但是此简单测试甚至无法正常工作。

remote php script 'remotescript.php' includes: 远程php脚本'remotescript.php'包括:

<script language='javascript' type='text/javascript'>
window.myValue=5;
</script>

Local page includes: 本地页面包括:

<div class='widget-content'>
<script language='javascript' src='remotescript.php' type='text/javascript'>
</script>
hi!
</div>
<script language='javascript' type='text/javascript'>
alert(window.myValue);
</script>

I get 'undefined' in the alert. 我在警报中得到“未定义”。

Any clue what I'm doing wrong, or if this should even work? 任何提示我在做什么错,或者这是否应该工作?
tyvmia tyvmia

Update: 更新:

Your external script remotescript.php doesn't work because it has <script> tags inside it - you need to remove those and just include the JavaScript code. 您的外部脚本remotescript.php不起作用,因为其中包含<script>标记-您需要删除这些标记,而仅包含JavaScript代码。 So in your simple example your remotescript.php should include just the following line: 因此,在您的简单示例中,remotescript.php应该仅包含以下行:

window.myValue=5;

Or you could use var : 或者您可以使用var

var myValue = 5;

(Note also that you don't need language='javascript' on any of your script elements.) (还要注意,您不需要在任何脚本元素上使用language='javascript' 。)

Original answer from original version of the question: 问题原始版本的原始答案

It won't work if you include JS statements inside a script element that is a link to an external script (this doesn't just apply to creating variables, it applies to any statements). 如果将JS语句包含在作为外部脚本链接的脚本元素内,则该方法将不起作用(这不仅适用于创建变量,还适用于任何语句)。 Close the external script and then start a new script element: 关闭外部脚本,然后启动一个新的脚本元素:

<div class='widget-content'>
<script language='javascript' src='http://example.com/files/blockip.php' type='text/javascript'></script>
<script>
var myValue=5;
</script>
hi!
</div>
<script language='javascript' type='text/javascript'>
alert(myValue);
</script>

If you declare globals in the external file that will also work. 如果您在外部文件中声明全局变量也将起作用。 Multiple scripts can access each other's variables if they are globals. 如果多个脚本是全局变量,则它们可以访问彼此的变量。

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

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