Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - Is the sort order of jQuery's $().each() guaranteed?

On one page of my site I have have a list of entries created by the user - standard HTML <ul> with <li> elements inside it.

I want to iterate through the list, but the order of elements is important.

Using jQuery $('.myList li').each(), can I guarantee that I will get the li elements in the order that they appear in the DOM?

From my tests so far, it appears that they do get iterated in the correct order, but I can't find anything that tells me it's guaranteed.

If it isn't guaranteed, what would be the next best alternative method for iterating through them in order?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So after reading the docs and coming away still not quite certain, I ended up diving in an actually reading the jQuery source code (thanks to @RoryMcCrossan's answer for prompting me on that).

In fact (contrary to what @RoryMcCrossan said), $().each() uses either for...in or for, depending on whether the input is an object or an array.

For 'array', it suffices to be an 'array-like' object, which is the case for a jQuery object because it contains a numbered list of elements and a length property.

Therefore, a call to $().each() will use for and not for...each as it is iterating over a jQuery object. And since we're using for, we know that we can guarantee the order of iteration for $().each() will match the order of the elements it is given.

So that leads me to ask a follow-up question of whether the order of elements given by the original query is guaranteed to be the same as they appear in the DOM. If so, then I should be okay.

The answer to that can be found in the question linked in the comments by @Mritunjay, and the answer is 'yes, they are returned in the order that they appear in the DOM.

So the final answer is that yes, I can use $('.myList li').each() and iterate through the list items in the order that they appear in the DOM.

Thanks for the help and the prompts guys. Much appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...