简体   繁体   中英

variable scope issue with javascript

In my application, originally those codes works:

var htm = "<div> My content </div>";   
$("#divprint").html(htm);
window.setTimeout('window.print()', 4000);

however, when I try to wrap it within an if statement, it won't print:

var canprint= $.cookie("actionprint");  
alert("I am outside " + canprint);
if(canprint == null){
    alert("I am inside");
    var htm = "<div> My content </div>";
    window.setTimeout('window.print()', 4000);
}

when I run this codes, I only got first alert: "I am outside null"

As javascript's scope is function level, I am wondering, why that if failed?

你能试试if语句吗?

if (!canprint)

OK. As weird it is:

Firstly, I tried to print out:

  console.log(typeof canprint, canprint);

amazingly, result is:

string null

so, I changed to if condition to:

if(canprint == "null")

then it can goes inside that if.

Though this is working, does anyone who can explain what has happened? This is really out of my expedition.

Remove the quote and parenthesis from setTimeout function

window.setTimeout(window.print, 4000);

And use something like this: jQuery check if Cookie exists, if not create it

var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }

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