简体   繁体   中英

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:

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... .

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.

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 .

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. 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.

Also you have mixed up CCT and 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:

  • A simple typo ( CCT vs CTT ).
  • If you use 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. To access global variables to just use them, not redefine them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM