jquery .each 迭代
如果您有超过 1 个具有相同类名的(动态)文本框,并使用 jquery 循环遍历每个所述文本框,您是否可以假设每次选择文本框的顺序都是相同的?
示例:
文本框 1 值 = 1 文本框 2 值 = 2 text box 3 value = 3
$(".textboxes").each(function(){
alert( $(this).val() );
});
每次都会以相同的顺序打印这些值吗?
If you have more than 1 (dynamic) text boxes with the same class name and use jquery to loop through each of said text boxes, can you assume that the order in which the textboxes are selected is the same every time?
Example:
Text box 1 value = 1
text box 2 value = 2
text box 3 value = 3
$(".textboxes").each(function(){
alert( $(this).val() );
});
Will it always print these values in the same order every time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
循环从头到尾,0 到最大长度 if > 0,因此如果您提供 html 选择器(它将按照结构/标记中定义的顺序选取元素),它将始终按照相同的顺序进行。
但是,如果您直接向 $.each 提供一个对象,由于没有标准方法或规则来规定排序方式,通常它会按照我见过的大多数解释器定义的顺序进行,但解释器不是'确实不应该遵守这个“规则”。
正如您所看到的,第二个 for 循环是实际执行的循环。
The loop starts from the beginning to the end, 0 to the max .length if > 0, so it will always go in the same order if you provide an html selector ( which would pick up elements in the order they are defined in the structure/markup ).
However if you fed an object to $.each directly, since there is no standard way or rule dictating how the ordering should be, usually it would go in the order they're defined for most interpreters I've seen, but interpreters aren't really supposed to obey this "rule".
As you can see the second for loop is the one that's actually executed.
jQuery 将从上到下并始终以相同的方式获取元素,因此每次的顺序都是相同的
jQuery will get the elements from top to bottom and always in the same way, so the order will be the same every time
这应该重要吗?如果您正在编写 .each 函数,则应该对每个元素执行相同的操作。否则你应该使用其他方法。因此,元素出现的顺序可能并不重要,如果确实如此,您可能已经发现了代码异味。
如果您正在寻找一种方法来单独识别列表中的每个元素,您可以尝试使用其 ID,例如:
这样做的优点是,如果预期的元素没有出现在列表中,则更容易识别确认。
Should it matter? If you're writing a .each function, you should be doing the same thing to every element. Otherwise you should use some other method. Hence, the order in which the elements appear probably shouldn't matter, and if it does, you may have discovered a code smell.
If you're looking for a way to individually identify each of the elements in the list, you could try using its ID, e.g:
This has the advantage that if an expected element doesn't appear in your list, it's a little easier to identify.