[英]javascript function variable always undefined
I am trying to code a simple function that checks a load of checkboxes with the specified class. 我正在尝试编写一个简单的函数来检查具有指定类的复选框的负载。 I want to use a variable to determine if the check all div has been clicked but the variable is always undefined:
我想使用一个变量来确定是否单击了check all div,但是该变量始终是未定义的:
var CCT;
$("#filterTitleTopic").click(function () {
console.log(CCT);
if (CCT == undefined || CCT == null || CCT == 2) {
$('input.topic').prop('checked', false);
var CTT = 1;
console.log("unchecking boxes...");
}
else if (CTT == 1) {
$('input.topic').prop('checked', true);
var CTT = 2;
console.log("checking boxes...");
}
});
console.log
always returns undefined
and unchecking boxes...
. console.log
总是返回undefined
和未unchecking boxes...
you only use var
when you want to define a variable, when you want to set a value to existing variable you do not add it. 仅在要定义变量时才使用
var
,而要为现有变量设置值时不添加它。
simply replace your code with this: 只需用以下代码替换您的代码:
var CCT;
$("#filterTitleTopic").click(function () {
console.log(CCT);
if (CCT == undefined || CCT == null || CCT == 2) {
$('input.topic').prop('checked', false);
CCT = 1;
console.log("unchecking boxes...");
}
else if (CCT == 1) {
$('input.topic').prop('checked', true);
CCT = 2;
console.log("checking boxes...");
}
});
Only assign the variable, don't reinitalize it with var
. 只分配变量,不要用
var
重新初始化它。
What happens if you do var CTT = 2
is that you initialize a new variable on the function scope which takes precendence over the variable defined in the global scope. 如果执行
var CTT = 2
会发生什么情况,就是在函数作用域上初始化了一个新变量,该变量优先于全局作用域中定义的变量。 Because this is allowed and sometimes even wanted you get no error there. 因为这是允许的,有时甚至希望您在此没有错误。 Because you initialize the variable on function scope however, you do not access the variable defined in line 1 anymore.
但是,由于您是在函数作用域上初始化变量的,因此您不再访问第1行中定义的变量。
Also you have mixed up CCT
and CTT
. 另外,您还混用了
CCT
和CTT
。
This works ( see fiddle ) 这有效( 请参阅小提琴 )
var CTT;
$("#filterTitleTopic").click(function () {
console.log(CTT);
if (CTT == undefined || CTT == null || CTT == 2) {
$('input.topic').prop('checked', false);
CTT = 1;
console.log("unchecking boxes...");
}
else if (CTT == 1) {
$('input.topic').prop('checked', true);
CTT = 2;
console.log("checking boxes...");
}
});
I guess there're two issues here: 我猜这里有两个问题:
CCT
vs CTT
). CCT
与CTT
)。 var foo
inside a function you get a brand new local function and you no longer have direct access to any foo
function you may have defined in outer escope. var foo
则将获得全新的局部函数,并且您将无法直接访问外部escope中定义的任何foo
函数。 To access global variables to just use them, not redefine them.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.