Recently encountered a problem, about the JavaScript loop, it really makes me more curious about the language (angry), words do not say, directly on the code:
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<script type= "Text/javascript" >
Window.onload=function () {
var p=document.getelementsbytagname ("P");
for (Var i=0;i<p.length;i++) {
P[i].onclick=function () {
alert (i);
}
}
}
</script>
</body> This is a click event, I started with the idea of clicking on the p above, triggering the Click event, popping the I value, but the result pops up 5 at a time.
Later after the query only learned : JS Event Processor Thread idle time will not run, resulting in the last run when the output is the last value of I.
That is, the event does not follow the loop when there is no click, and the external loop is still in progress, which results in the end of the run of the code at the beginning, and then only the last value of the event click.
So in order to prevent this, I tried to add "()" in the back to make it self-running function to test, found that finally can play a normal value, but this is not what I want. Because I still want to click on the bounce value instead of loading
After the auto-bounce value.
After the correction, thought, since the event is not followed by the loop to get the value, why not directly assign the value of "I" directly to p[i]?
So:
Window.onload=function () {
var p=document.getelementsbytagname ("P");
for (Var i=0;i<p.length;i++) {
P[i].i=i; I'll save it here.
P[i].onclick=function () {
alert (THIS.I);
}
}
}
The result runs fine.
Here I use this , about this point of knowledge for me this little Moe is really very difficult,
Next Updated blog post I'm going to write it and get it all figured out.
The problem of a loop that JavaScript encounters