全局变量在控制台中显示为undefined - 不习惯

时间:2013-08-06 01:08:26

标签: javascript global-variables

这是我模块中的第一个javascript声明:

<script type='text/javascript'>
var json_meets;
var teams;
var my_meet;

window.onload = function() {
    AJAX( '/ajax/getFacilities.html','','populate_datalist_from_array','facilities' );
    AJAX( '/ajax/getAssociations.html','','process_associations','datalist_for_new_team_Association' );
$( "#add_team_dialog" ).dialog({ autoOpen: false });
    window.json_meets = { "meets" : [] };
    window.teams = [];
    window.my_meet = {
        "meet_name" : "",
        "meet_date" : "",
        "meet_id"   : "",
        "meet_location" : "",
        "teams"     : []
    };
}

稍后我会包含一个或两个声明此函数的文件:

function submitTeamToAdd( obj ) {
var doit = 0;

// get Display name of team in input box
var team = document.getElementById( 'add_team_input' ).value;

for ( var i = 0 ; i < window.my_meet.teams.length ; i++ ) {
    if ( getTeamDisplayName( window.my_meet.teams[i] ) == team ) {
        alert( team + ' is already participating.' );
        document.getElementById( 'add_team_input' ).value = '';
        return;
    } 
}   

for ( var i = 0 ; i < window.teams.length ; i++ ) {
    if ( getTeamDisplayName( window.teams[i] ) == team ) {
        doit = 1;
        break;
    }   
}
if ( doit == 1 ) {
    putTeamOnList( team , obj );
} else {
    // open the dialog to add a new team to the database
    openDialog( 'add_team_dialog' );

    // pass thru the name of the team that was entered clear out legacies.
    document.getElementById( 'add_new_team_Name' ).value = team;
    document.getElementById( 'add_new_team_Nickname' ).value = '';
    document.getElementById( 'add_new_team_Association' ).value = '';
    document.getElementById( 'add_new_team_Mascot' ).value = '';
    document.getElementById( 'add_new_team_Classification' ).value = '';
}
}

当该函数触发时,控制台抛出:

TypeError: window.my_meet is undefined

它是如何定义的?变量在window.onload函数中声明并初始化。我可以理解它们本质上是空的,但这并不能使它们不确定,对吧?它应该只是一个长度为0的数组。

2 个答案:

答案 0 :(得分:2)

它未定义,因为您没有定义它。您声明了它,但在您的函数尝试访问它时它仍然具有值undefined

加载完所有资源(包括图像)后,

window.onload会激活,但您似乎在此之前调用了您的函数。在调用函数之前,您需要等待AJAX​​调用完成。

答案 1 :(得分:0)

尝试在任何地方使用窗口['my_meet'] ,而不是 window.my_meet