无法获取全局变量 [英] Can't get global variable

查看:174
本文介绍了无法获取全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是窗口
但我只是无法访问它。为什么?



这里的代码在一个位于js文件夹中的函数中:

  function update_match(slot,match,s){
$(#match+ slot +i)。
console.log(window);
console.log(window.saves1); //未定义
console.log(window.external.saves1); // undefined
(slot == 1)? window.saves1.item = s:window.saves2.item = s;

$ / code $ / pre
$ b $变量是这样创建的:

 函数set_global(name,pos,ab,needSave,s){
window.saves1 = {item:s};
window.saves2 = {item:s};
}

在js / main.js文件中。



文件结构如下所示:

  index.php(php代码运行并调用update_match ())
js - main.js
- read_match.js


解决方案

您正在运行update_match过早。



看起来,当您运行update_match时,全局变量尚未定义。它们是在稍后创建的。但是因为console.log在当时没有回显窗口对象的快照,所以它显示了全局变量,因为在脚本结束时它们被创建并且console.log显示已完成窗口Object。 p>

为了解决您的问题,稍后运行update_match,可以在文档准备就绪后使用setTimeout函数,也可以延迟一段时间:

  setTimeout(function(){update_match();},500); 

要在文档准备好后运行该函数,请看这篇文章:



jQuery Mobile:文档准备与页面事件



你可以这样做:

  $ (document).ready(function(){

update_match();

});


Here is the window: so now, when I scroll down (the children appear in the same fashion as displayed above, all way long), I see what I want: but I just fail to access it. Why?

Here the code, in a function that lies in a js folder:

function update_match(slot, match, s) {
    $("#match" + slot + " i").text(match);
    console.log(window);
    console.log(window.saves1);          // undefined
    console.log(window.external.saves1); // undefined
    (slot == 1) ? window.saves1.item = s : window.saves2.item = s;
}

The variables are created like this:

function set_global(name, pos, ab, needSave, s) {
    window.saves1 = {item: s};
    window.saves2 = {item: s};
}

inside js/main.js file.

The file structure is like this:

index.php (where the php code runs and calls update_match())
js - main.js
   - read_match.js

解决方案

You are running update_match too early.

It seems that while you are running the update_match, the global variables aren't defined yet. They are created later. But because console.log, does not echo out a snapshot of the window object at that time, it shows the global variables, because at the end of your script they got created and console.log shows the "finished" window Object.

To solve your issue, run the update_match later, either after the document is ready or using the setTimeout function with a reasonable delay:

setTimeout(function(){ update_match(); }, 500);

To run the function after the document is ready, take look at this post:

jQuery Mobile: document ready vs page events

You could do it by:

$(document).ready(function() { 

update_match();

});

这篇关于无法获取全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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