【问题标题】:The changed variable value can not be accessed after a change within the function在函数内发生更改后无法访问更改的变量值
【发布时间】:2018-12-02 14:31:33
【问题描述】:
        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);

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

【问题讨论】:

  • 你如何测试它?因为console.log("outside function: " + getFileName); 将在调用onChange 回调之前执行。那时getFileName 的值仅为null
  • 非常确定您需要在每条语句的末尾添加一些分号。
  • 是的,我完全忽略了这一点。认为这将是问题所在。你知道我如何在 onChange 函数之后检索它。
  • 有需要的拨打$('...').change(() => {/* Your code */})

标签: javascript jquery variables scope global-variables


【解决方案1】:

就像在 cmets 中提到的,这些行不是按照它们被记录的回调原因的顺序执行的。

你应该这样做

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多