简体   繁体   English

将参数传递给匿名 Javascript 函数

[英]Passing arguments to anonymous Javascript functions

Consider the code below:考虑下面的代码:

this.usedIds = 0;

this.SendData = function(data)
{
    var id = this.usedIds;
    this.usedIds++;

    this.xmlHttpThing.open("POST", "/Upload.aspx", true);
    this.xmlHttpThing.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    var currentObject = this;
    this.xmlHttpThing.onreadystatechange = function() { currentObject.UploadComplete(id) };
    this.xmlHttpThing.send(data);
};
this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {
        //First time id is 0
        //Second time id is 0                 <<<--------- Why??
        //Third time id is 1
        //Fourth time id is 2
        //Fifth time id is 3 ....         

        this.SendData("blabla");
    }
};

Why does the id I pass to the anonymous function get delayed by one call after the first call?为什么我传递给匿名函数的 id 在第一次调用后被一次调用延迟?

Only seems to be this way in Firefox, in IE the UploadComplete receive the ids in the correct order.在 Firefox 中似乎只有这种方式,在 IE 中, UploadComplete以正确的顺序接收 ID。

In the second loop I can stop the debugger at the send(data)-line and confirm that the id is actually 1 but when I get to the UploadComplete it turns out to be 0 in that argument :(在第二个循环中,我可以在 send(data) 行停止调试器并确认 id 实际上为 1,但是当我到达UploadComplete时,该参数中的值为 0 :(

EDIT: Found solution:编辑:找到解决方案:
Disable Console-logging in FireBug.在 FireBug 中禁用控制台日志记录。

I had the same problem too in the past.我过去也遇到过同样的问题。 I don't remember exactly what caused it, but I fixed it by moving the increment to the response handler.我不记得到底是什么导致了它,但我通过将增量移动到响应处理程序来修复它。

this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {      
        this.usedIDs++;
        this.SendData("blabla");
    }
};

Edit: after thinking about it, my case may have been different from yours.编辑:仔细想想,我的情况可能与你的不同。 Why not increment this.usedIDs when you assign id ?为什么在分配id时不增加this.usedIDs

var id = this.usedIDs++;

在 Firebug 中禁用控制台日志解决了这个问题!

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

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