javascript - 函数内更改后,无法访问更改后的变量值

标签 javascript jquery variables scope global-variables

        var getFileName = null

        $('#fileInput').change(function() {
            var props = $('#fileInput').prop('files'),
                file = props[0]
            getFileName = "" + file.name
            console.log("inside function: " + getFileName)
        })


        // selected file
        console.log("outside function: " + getFileName);

变量在函数内部正确更改,但我无法在函数外部获取更改后的值。我想我忽略了一些东西,但目前无法修复它。 😅

最佳答案

就像评论中提到的那样,这些行不会按照它们被注意到的回调原因执行的顺序执行。

你可能应该这样做

    var getFileName = null; // global variable

    $('#fileInput').change(function() {
        var props = $('#fileInput').prop('files'),
            file = props[0],
            getFileName = "" + file.name
        ;
        console.log("inside function: " + getFileName); // log in callback
        checkOutside();
    })

    function checkOutside(){
        // output global variable after its changed in callback of "change"-event
        console.log("outside function: " + getFileName);
    }

关于javascript - 函数内更改后,无法访问更改后的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50999350/

相关文章:

javascript - AngularJS : Undefined value returned in controller

javascript - 使用不同的上下文通过复选框进行单独的 jquery ajax 调用

javascript - 推迟回调直到 setTimeout 完成

javascript - 通过 JSON 检索数字并存储在变量中

java - 渲染 JSP 页面后设置 ng-model

javascript - 防止在加载页面上滚动

javascript - js文件类型错误: Dispatch is not a Function in actions.

javascript - 使用 jquery 获取选中的复选框的 id

javascript - 为什么我的变量根据它们是数组还是整数而有所不同?

c# - 在 C# 中设置/获取命令行系统变量