jQuery的$()。each()是否有保证? [英] Is the sort order of jQuery's $().each() guaranteed?

查看:109
本文介绍了jQuery的$()。each()是否有保证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我网站的一页上,我有一份用户创建的条目列表 - 标准HTML < ul> ,其中< li> ;

里面的元素



我想遍历列表,但元素的顺序很重要。 b

使用jQuery $('。myList li')。each(),我可以保证我会得到 li 元素按照它们出现在DOM中的顺序吗?



从我到目前为止的测试中看来,它们确实得到了正确的迭代订单,但我找不到任何告诉我它是有保证的。



如果不能保证,那么下一个最好的替代方法是什么?为什么在阅读这些文档后离开仍然不太确定,我最终在实际阅读jQuery时潜水源代码(感谢@ RoryMcCrossan的回答,提示我)



事实上(续($)$> $()。each()使用作为...... in for 取决于输入是对象还是数组

数组就足够了,因为它包含一个数组元素列表和一个长度属性,所以它就足够成为一个类似数组的对象。 / p>

因此,调用 $()。each()时会使用 code>而不是 for ... each ,因为它遍历一个jQuery对象。因为我们使用作为,所以我们知道我们可以保证 $()的迭代次序。each()将匹配给定元素的顺序。



因此,这导致我询问后续问题,即原始查询给出的元素顺序保证与它们​​在DOM中出现的相同。如果是这样,那么我应该没问题。



可以在

所以最终答案是,可以使用 $('。 myList li')。each()并按照它们出现在DOM中的顺序遍历列表项。



感谢您的帮助和提示家伙。非常感谢。


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?

解决方案

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.

这篇关于jQuery的$()。each()是否有保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆