【问题标题】:variable scope issue with javascriptjavascript的可变范围问题
【发布时间】:2014-01-23 04:26:59
【问题描述】:

在我的应用程序中,最初这些代码有效:

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

但是,当我尝试将其包装在 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);
}

当我运行此代码时,我只收到第一个警报:“我在 null 之外”

由于 javascript 的范围是函数级别,我想知道,如果失败了,为什么会这样?

【问题讨论】:

  • 我在您的代码中没有看到任何函数定义。顺便说一句,console.log(typeof canprint, canprint);
  • 是不是忘记在变量htm的声明中加双引号了?
  • 您的代码是否像您的帖子一样缺少右引号?
  • $.cookie() 对于不存在的道具返回undefined
  • @BlackSheep - 我认为这是真正的原因

标签: javascript jquery html


【解决方案1】:

你能试试 if 语句吗,

if (!canprint)

【讨论】:

    【解决方案2】:

    好的。很奇怪:

    首先,我尝试打印出来:

      console.log(typeof canprint, canprint);
    

    令人惊讶的是,结果是:

    string null
    

    所以,我将if条件改为:

    if(canprint == "null")
    

    那么它可以进入那个 if。

    虽然这行得通,但有谁能解释发生了什么吗? 这真的是我的探险队之外的事情。

    【讨论】:

      【解决方案3】:

      从 setTimeout 函数中删除引号和括号

      window.setTimeout(window.print, 4000);
      

      并使用如下内容:jQuery check if Cookie exists, if not create it

      var CookieSet = $.cookie('cookietitle', 'yourvalue');
      
           if (CookieSet == null) {
                // Do Nothing
           }
           if (jQuery.cookie('cookietitle')) {
                // Reactions
           }
      

      【讨论】:

      • 虽然这是一个合理的建议,但没有必要;原来的电话也可以。它没有回答问题。
      • 这似乎不对。它会在检查它是否已经设置之前设置 cookie。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      相关资源
      最近更新 更多