Some time ago, when I did something and encountered several "missing objects" errors, I summarized the errors, which are related to the execution sequence of JavaScript, But I searched for them, javaScript does not seem to have the concept of a thread, and there is only the execution order (after a part is completed, another part is started). This situation is generally usedSettiemoutOrXMLHttpRequest(Asynchronous.
I. The first step is the execution sequence of the asynchronous XMLHttpRequest (async) callback function (callback ).At first, I wroteCodeBut variable B is always empty (asynchronous request is normal ):
VaRA= "";
......
Request. onreadystatechange = function (data ){
If (request. readystate = 4 & request. Status = 200 ){
A= Data;
}
}
Request. Open ('get', path,True); // If it is set to false, it is not asynchronous and the code will be executed in order.
VaRB=A. Length;
Finally, put the data operation in the callback function to solve the problem and change it to the following:
Request. onreadystatechange = function (data ){
If (request. readystate = 4 & request. Status = 200 ){
A= Data;
VaRB=A. Length;
}
}
II. The second problem is how to obtain dynamically generated DOM elements in JavaScript., Use JavaScript to generate the interface, and then perform operations on the generated elements. The error "Missing Object" is always reported ". The simplified code is as follows:
Window. onload = function (){
VaR body = Document. getelementsbytagname ("body") [0];
VaR elmt = Document. createelement ("p ");
Elmt. ID = "hello ";
VaR TXT = Document. createtextnode ("hello ");
Elmt. appendchild (txt );
VaR did = Document. getelementbyid ("hello ");
Alert (did. ID );
Body. appendchild (elmt );
}
The object created with createelement cannot be obtained. However, this object has been created before the call. Later, we found that,This object has not been added to the entire document before being operated.Adjusted the code order:
Body. appendchild (elmt );
VaR did = Document. getelementbyid ("hello ");
Alert (did. ID );
Running properly. But there are new problems. When I put it in a slightly complex environment, I can only add all DOM elements to the document at the last time, that isAppendchild (elmt)Not possibleGetelementbyid (elmtid)As a result, Google/Baidu found that this is a common and basic problem.SetTimeoutWonderful use,Let JavaScript code be executed in an unordered manner:
SetTimeout (Function (){
VaR did = Document. getelementbyid ("hello ");
Alert (did. ID );
},0);
Body. appendchild (elmt );
In this way, even if the setTimeout delay is set to 0, the functions in the setTimeout will be executed after all the code is executed, so the problem is solved.
Refer:
Realazy: recognize the setTimeout with a delay of 0
Javascriptkata:
Ajax, JavaScript and threads: The final truth
Fitzblog:
Nine JavaScript gotchas