jQuery的$()。each()是否有保证?

编程入门 行业动态 更新时间:2024-10-26 22:21:57
本文介绍了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()是否有保证?

本文发布于:2023-11-06 08:00:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!