Does jQuery always iterate through DOMs in order in which they are found in the code?

独自空忆成欢 提交于 2020-01-01 08:02:50

问题


Say, for example, I have a sortable list:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

What I want to know is, if I make a jQuery call such as the following:

$.each($('li'), function(key, item) {...});

Can I expect jQuery to go through the entries from top to bottom? I've run a few tests, and tried rearranging items dynamically using jQueryUI, and so far, it seems to always run in order. But can this always be expected? Or is it dumb luck that I've not run into anything so far to make me think otherwise...?


回答1:


"Can I expect jQuery to go through the entries from top to bottom?"

Yes. They are iterated by numeric index from 0 to length - 1.

The elements will always be returned in the order that they appear in the DOM.

"I've run a few tests, and tried rearranging items dynamically..."

It doesn't give consideration to CSS positioning if that's what you mean. If you're changing their actual location in the DOM, then you'd only see the updates if you re-select them from the DOM.




回答2:


It didn't use to, but since jQuery 1.3.2 selectors return elements in the order in which they are found in the DOM.




回答3:


There is no where in the docs that promise this behavior, but this the way it's currently implemented.

That said, I can't see a reason why would they change this behavior.



来源:https://stackoverflow.com/questions/9182654/does-jquery-always-iterate-through-doms-in-order-in-which-they-are-found-in-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!