javascript - 访问 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)
}
}
});
解决方案
你不能这样做。
它是函数的局部变量,不能在函数外访问。还有另一种称为全局变量的变量,可以在脚本中的任何位置访问。
要理解这一点,请考虑以下示例,
// 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);
};
您可能想先了解变量范围。查看此博客。
推荐阅读
- java - 使用 JAVA 生成可填写/可编辑的 PDF
- python - 在 pandas 中组合两个表格并将它们可视化为面积图
- python - Django:从两个日期时间对象中减去时间
- c# - 具有多个页面的小型响应式 WPF 应用程序
- intersystems-iris - 加密虹膜 ODBC 64 位
- angular - FileReader.onload 从未以角度触发
- spring-cloud-contract - Spring Cloud合约错误'期望等于
关闭 - json - Powershell:使用来自 json 的值作为参数默认值
- ios - 如何在中继上使用 share()?
- angular - 找不到管道异步 / ionic-ng / CommonModule 已导入