简体   繁体   English

javascript的变量范围问题

[英]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: 但是,当我尝试将其包装在if语句中时,它将不会打印:

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? 由于javascript的范围是功能级别,我想知道,为什么如果失败?

你能试试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条件:

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 从setTimeout函数中删除引号和括号

window.setTimeout(window.print, 4000);

And use something like this: jQuery check if Cookie exists, if not create it 并使用这样的东西: jQuery检查Cookie是否存在,如果没有创建它

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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