全局变量未全局更新

时间:2020-05-05 00:13:11

标签: javascript json function global-variables

我正在尝试创建一个网页以使用JSON可视化家谱。我正在使用uploadJSON()函数将文件中的JSON数据存储到全局变量tree中,在我尝试在另一个函数中访问tree之前,它似乎一直有效。当我在console.log(tree);中执行addToDropDown()时,它在控制台中显示为未定义。我尝试在初始化时将tree设置为默认值"Testing",但在我调用uploadJSON()时不会被覆盖。

let tree;
let dropDown;

window.onload = function() {

    // Upload JSON File
    document.getElementById( 'upload-button' ).onclick = function() { uploadJSON(); };

    // Get Dropdown
    dropDown = document.getElementById( 'family-memeber-select' );

}

function uploadJSON() {

    let files = document.getElementById( 'upload-file' ).files;
    if( files.length <= 0 ) {
        return false;
    }

    let fr = new FileReader();

    fr.onload = function( e ) {
        console.log( e );
        let result = JSON.parse( e.target.result );
        tree = result;
        console.log(tree); // This outputs the tree object from the JSON file as expected
    }

    fr.readAsText( files.item(0) );


    addToDropdown();
}


function addToDropdown()  {
    // Add all family members to a dropdown list

    console.log( tree );
}

0 个答案:

没有答案