Home > Web Front-end > JS Tutorial > Issues you need to pay attention to when using NodeList_javascript tips

Issues you need to pay attention to when using NodeList_javascript tips

WBOY
Release: 2016-05-16 17:41:07
Original
1402 people have browsed it

So they always have the latest and most accurate information. Essentially, all NodeList objects are queries that run in real time when accessing a DOM document. For example, the following code will cause an infinite loop:

Copy code The code is as follows:



First get the page For all divs in the div, since this collection (divObj) is "dynamic", whenever a new div is inserted into the page, divObj will add the newly added div. In other words, as long as divObj is accessed, it will be queried again and divObj will be updated again. Therefore, the above code will cause an infinite loop, because a new div is inserted during each loop, and each loop must evaluate the condition i.

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

Copy code The code is as follows:



In this example the second variable (len) is initialized. Since len stores a snapshot of divObj.length at the beginning of the loop, the infinite loop in the previous example will be avoided.

Summary: Generally speaking, the number of visits to NodeList should be minimized. Because every time a NodeList is accessed, a document-based query is run. Therefore, you can consider caching the values ​​obtained from NodeList, as shown in Example 2!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template