Can't get global variable

℡╲_俬逩灬. 提交于 2019-12-25 05:43:32

问题


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

回答1:


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();

});


来源:https://stackoverflow.com/questions/32554248/cant-get-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!