难道这就是JavaScript中的"闭包"

其实对于JavaScript中的"闭包"还没真正理解,这次在实际Coding中似乎遇到了"闭包"的问题,仅此摘录,以待深究.

表现为jQuery的post方法回调function内始终"拿"不到外部变量.

将代码改写成如下模式,成功了.

var reflesh = "Y";
function onOk()
{
     var pingZheng = document.getElementById("txtPinZhenNum").value;
     if (pingZheng == "")
     {
                alert("凭证号为空");
                document.getElementById("hdBtnExport").click();
                return
     }
     var anchors = document.getElementById("DbList").getElementsByTagName("a");
            
     for (var i = 0; i < anchors.length; i++) {
          if (anchors[i].style.background == "yellow")
          {
               var curr_asp_anchor = $(anchors[i]).prev()[0];
               var id = anchors[i].attributes.getNamedItem("name").value;
               $.post("CwNCExport.aspx", { getresult: "Y", id:id,pingZheng: pingZheng }, function (result) {
                        foo(curr_asp_anchor, result);
                    });
          }
     }
}

function foo(arr, result)
{
    if (result == "Y") {
        arr.click();
        var tid = setInterval(function () {
            if (reflesh == "Y") {
                window.location.href = window.location.href;
                clearInterval(tid);
            }
            reflesh = "N";
        }, 3000);
    }
    else {
        alert("凭证号重复");
        document.getElementById("txtPinZhenNum").value = pingZheng;
        document.getElementById("hdBtnExport").click();
    }
}

 

posted @ 2016-08-31 10:07  轴轴  阅读(214)  评论(0编辑  收藏  举报