鉴于以下代码,我不确定为什么我可以检索 longAndObscureVariableName 但不能检索 anotherLongObscureVariableName。您能否解释一下,并展示如何使 anotherLongObscureVariableName 可从 jsFileNumberTwo.js 访问?
HTML 文档的头部最初包含:
<script type="text/javascript" id="my_globals">
var longAndObscureVariableName = "foo";
</script>
<script type="text/javascript" src="jsFileNumberOne.js" /></script>
<script type="text/javascript" src="jsFileNumberTwo.js" /></script>
Javascript 文件 jsFileNumberOne.js 包含以下代码,它将另一个全局变量添加到 #my_globals 元素中:
jQuery(document).ready(function() {
// Store the initial variables, to which we will add more
var initialVars = jQuery('#my_globals').html();
// Define content for script tag:
var scriptContent = initialVars;
// Add to the script content
scriptContent += 'var anotherLongObscureVariableName = "bar";\n';
function insertNewInfo() {
jQuery('#my_globals').html(scriptContent);
};
insertNewInfo();
});
当 jsNumberOne.js 执行时,#my_globals 更改为:
<script type="text/javascript" id="my_globals">
var longAndObscureVariableName = "foo";
var anotherLongAndObscureVariableName = "bar";
</script>
Javascript 文件 jsFileNumberTwo.js 包含此代码,试图找出 anotherLongAndObscureVariableName 的值:
jQuery(document).ready(function($) {
console.log('longAndObscureVariableName'); // log displays "foo"
console.log('anotherLongAndObscureVariableName'); // log displays "Uncaught ReferenceError: anotherLongAndObscureVariableName is not defined"
console.log('window.anotherLongAndObscureVariableName'); // log displays "undefined"
setTimeout(function(){
console.log(window.anotherLongAndObscureVariableName);
},2000); // log still displays "undefined"
});
我无法从 jsFileNumberTwo.js 中检索 anotherLongAndObscureVariableName,即使我认为我是通过将其放入 HTML 文档的头部来将其添加到全局范围的。
这是范围问题吗?这是时间/顺序问题吗?我认为 jsFileNumberTwo.js 可能在 jsFileNumberOne.js 执行之前访问头部内容,但即使添加了 setTimeout 函数,我仍然得到“未定义”。
这是怎么回事?我怎样才能做到这一点?
最佳答案
脚本从上到下运行。因此第二个脚本修改了第一个脚本,该脚本已经运行并且不会再次运行,因此实际上没有任何效果。
此外,您应该在窗口上放置一些东西来创建全局变量。
所以替换
scriptContent += 'var anotherLongObscureVariableName = "bar";\n';
function insertNewInfo() {
jQuery('#my_globals').html(scriptContent);
};
insertNewInfo();
与
window.anotherLongAndObscureVariableName = "bar";
,
var longAndObscureVariableName = "foo";
与
window.longAndObscureVariableName = "foo";
关于javascript - 看似已定义的 JavaScript 变量会引发未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31884772/