使用Array.prototype.sort.call对HTMLCollection进行排序 [英] Using Array.prototype.sort.call to sort a HTMLCollection

查看:154
本文介绍了使用Array.prototype.sort.call对HTMLCollection进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var down = function(a,b){alert(a)} 
Array.prototype.sort.call(table.tBodies [0] .childNodes,down)
Array.prototype.sort.call([0,1,2,3],down)

为什么我不会收到来自第一个排序调用的警报? 转换 NodeList 到数组中:

  var elements = [] .slice.call(table.tBodies [0 ] .childNodes); 

然后通常调用 sort >: p>

  elements.sort(down); 

似乎 sort 无法处理类似数组的对象。这可能是因为 NodeList 没有提供任何方法来更改列表,但是 sort 对数组进行排序 com / ELS5_HTML.htm#Section_15.4.4.11rel =noreferrer>规范:
$ b


执行一个实现 - 依赖于对 obj 的[[Get]],[[Put]]和[[Delete]]内部方法调用的顺序。

我假设 NodeList 没有这些内部方法。但这只是一个假设。也可能是这是依赖于实现的。



我还建议你使用 .children [MDN] ,而不是 .childNodes 只能获取元素节点。 更新:或者 .rows [DOM Spec]

var down=function(a,b){alert(a)}
Array.prototype.sort.call(table.tBodies[0].childNodes,down)
Array.prototype.sort.call([0,1,2,3],down)

Why do I not get alerts from the first sort call?

解决方案

Convert the NodeList to an array first:

var elements = [].slice.call(table.tBodies[0].childNodes);

and then call sort normally:

elements.sort(down);

It seems sort cannot handle array-like objects. This is probably because NodeList does not provide any methods to change the list, but sort sorts the array in-place.

Update: For more information, from the specification:

Perform an implementation-dependent sequence of calls to the [[Get]] , [[Put]], and [[Delete]] internal methods of obj.

I assume NodeLists don't have these internal methods. But this is really just an assumption. It could also be that this is implementation dependent.

I also suggest you use .children [MDN] instead of .childNodes to only get element nodes. Update: Or .rows [DOM Spec] as @patrick suggests.

这篇关于使用Array.prototype.sort.call对HTMLCollection进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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