0

这是我模块中的第一个 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 的数组。

4

2 回答 2

2

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

window.onload在所有资源(包括图像)加载后触发,但您似乎在此之前调用了您的函数。在调用函数之前,您需要等待 AJAX 调用完成。

于 2013-08-06T01:16:52.357 回答
0

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

于 2013-08-06T01:16:57.023 回答