[英]How can I access a variable from within a nested function?
I need to access a variable from within a nested function like so: 我需要从嵌套函数中访问变量,如下所示:
$(function() {
var key = getRandomKey(dictionary);
resetInputRow(dictionary[key]);
$("#button").click( function() {
var answer = key;
// check if user input matches answer (the original key)
...
// reset key for next check
var key = randomKey(dictionary);
resetInputRow(dictionary[key]);
});
});
So far, this hasn't been working. 到目前为止,这还没有奏效。 When I check the value of
answer
it is undefined. 当我检查
answer
的值时,它是不确定的。
It is because you have declared a local variable called key
, because you have used var
before var key = randomKey(current_dict);
这是因为您声明了一个称为
key
的局部变量,因为您在var key = randomKey(current_dict);
之前使用了var
var key = randomKey(current_dict);
in the click handler. 在点击处理程序中。 Since you have a local variable the variable external scope(closure) will not be accessed.
由于您具有局部变量,因此不会访问变量外部作用域(关闭)。
$("#button").click(function () {
var answer = key;
// check if user input matches answer (the original key)
...
// reset key for next check
key = randomKey(dictionary);
resetInputRow(dictionary[key]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.