JavaScript uses nodelist issues to be aware of _javascript tips

Source: Internet
Author: User

As a result, they always keep the latest and most accurate information. Essentially, all NodeList objects are queries that run in real time when accessing DOM documents. For example, the following code can cause an infinite loop:

Copy Code code as follows:

<script type= "Text/javascript" >
Window.onload=function () {
var divobj=document.getelementsbytagname (' div ');
for (Var i=0;i<divobj.length;i++) {
var d=document.createelement ("div");
Document.body.appendChild (d);
}
}
</script>

First get all the div on the page, because this set (Divobj) is "dynamic", so whenever a new div is inserted into the page, Divobj adds the newly added Div. In other words, as long as access to Divobj, will requery, update divobj. So, the above code, there will be a dead loop, because each time the loop is inserted a new div, and each loop to the condition i<divobj.length evaluation, meaning that will run the obtained all <div> queries.

If you want to iterate over a nodelist, it is best to use the Length property to initialize the second variable and then compare the iterator with that variable. As shown in the following code:

Copy Code code as follows:

<script type= "Text/javascript" >
Window.onload=function () {
var divobj=document.getelementsbytagname (' div ');
for (Var i=0,len=divobj.length;i<len;i++) {
var d=document.createelement ("div");
Document.body.appendChild (d);
}
}
</script>

In this example, the second variable (len) is initialized. Since Len holds a snapshot of the divobj.length at the beginning of the loop, the dead loop of the previous example is avoided.

Summary: In general, the number of visits to nodelist should be minimized. Because every time you access nodelist, you run a document based query. So, consider caching the values you get from nodelist, as shown in example two!

Related Article

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.