The problem of a loop that JavaScript encounters

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.