开发者

jQuery each() behavior if changing DOM within loop

What is the behavior of jquery when using each() loop? Is it:

  1. look for the first object, execute function, look for the next object...
  2. gather all objects in a container, then execute the function on each of them
  3. other (what exactly?)

An example, where it is relevant:

<div id="a">
   A
   <div id="b">
      B
   </div>
</div>
<div id="c">
    C
</div>

If I execute this javascript:

$('div').each(function(index){
   alert($(this).html());
   $(this).remove();开发者_运维百科
}

Will I see three alerts or only two?


Regardless of what action you will perform on a selection, jQuery will make that selection before applying that action. By which I mean $('div') is a selector, the selection process happens before and regardless of the other chained methods (such as each()). This is a product of the language, since $() must be evaluated before a method can be called upon it.

If that selection grabbed three divs from your page, then there are now 3 jQuery objects in a list ready to be iterated over. You can prove this by doing:

$('div').length

Thus you are iterating over an array with three indexes (0, 1, 2), if you remove the div from the DOM for index 1, the next iteration of the each() callback will still be for the object at index 2. Checkout this live demo for proof:

DEMO: http://jsfiddle.net/marcuswhybrow/HYJa4/


jQuery will behave as you've described in #2. You'll see three alerts:

  1. "A <div> B </div>"
  2. "B"
  3. "C"

However, since div B is inside div A, it will be removed with div A. jQuery still knows about it, and will alert its contents, but it will have already been removed by that time. So, although you get three alerts, you only have two removes (since it removes child elements).


2 is the answer.

jQuery gathers a list of matching elements, then loops over the list.

One important think though, do not remove any element that can be mached that has not already been processed or you will risk getting a reference not found error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜