首页 > 解决方案 > 访问 Javascript 函数变量

问题描述

JavaScript 新手。我正在尝试从函数中访问变量以触发 ajax 调用。非常感谢任何帮助。

document.onkeydown = logKey;
i = 0;
function logKey(e) {
    var keys = i += 1;
};
console.log(keys);

未捕获的 ReferenceError:未定义键

正如@sanketd617 所指出的,这是一个范围问题。我使用了@Arun P Jonny 的以下内容

$(document).ready(function () {
    var idleTime = 0;
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); 

    //Zero the idle timer on keypress.
    $(this).on('keypress', function (e) {
        console.log('reset: ', e.type)
        idleTime = 0;
    });


    function timerIncrement() {
        idleTime = idleTime + 1;
        if (idleTime > 1) {
            console.log(idleTime)
        }
    }
});

标签: javascriptvariables

解决方案


你不能这样做。

它是函数的局部变量,不能在函数外访问。还有另一种称为全局变量的变量,可以在脚本中的任何位置访问。

要理解这一点,请考虑以下示例,

// Global variable
var x = 10;

function demo() {
    // Local variable of demo
    var y = 20;

    // This is valid
    console.log(y); // 20

    // This is also valid
    console.log(x); // 10
}

// This is valid
console.log(x); // 10

// This is not valid
console.log(y); // error

出于您的目的,我认为您想在keys每次按下键时 console.log() 变量的值。这可以按如下方式完成:

document.onkeydown = logKey; 
var i = 0;     

function logKey(e) { 
    var keys = i += 1;
    console.log(keys)

    // If you notice, you can just remove the varible keys
    // Because it's just the value of i after increment
    console.log(i);
}; 

您可能想先了解变量范围。查看博客。


推荐阅读