JavaScript 节点列表
有没有办法连接 2 个 document.getElementsByTagName 调用返回的 2 个 NodeList?
假设我有以下代码,
var inputs = documentElement.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
我想循环遍历结果。 可以在一个循环中吗?
先感谢您!
is there a way to join 2 NodeLists returned by 2 calls of document.getElementsByTagName?
Say, I have the following code
var inputs = documentElement.getElementsByTagName('input');
var selects = document.getElementsByTagName('select');
I want to loop through the results. Is it possible in one loop?
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
似乎您可以使用相同的 Array.prototype.slice.call 使 args 类似数组的对象成为数组。 (参见此处)
Seems like you can use the same Array.prototype.slice.call that makes the args array-like object become an array. (See here)
据我所知,
NodeList
类型是不可变的(参见 例如本文),这意味着您必须生成自己的对象。一个简单的方法就是创建一个数组并将所有元素复制到该数组中。
然后,
all
变量包含两组节点的并集。As far as I know, the
NodeList
type is immutable (see this article for example), which means you'll have to generate your own object.A simple method would just be to create an array and copy all the elements into that array.
The
all
variable then contains the union of the two sets of nodes.您无法加入它们,但您仍然可以在一个循环中按顺序循环它们,如下所示:
或者,使用 jQuery,您可以一次性选择它们:
You can't join them, but you can still loop through them sequentially in one loop like this:
Alternatively, using jQuery, you could select them all in one go:
console.log( mergeNodeLists( 输入, 选择 ) ); // => [输入、选择]
console.log( mergeNodeLists( inputs, selects ) ); // => [input, select]
我把这个放在一起。 为每个循环执行 if 和 .length 可能会产生一些开销,但我认为除非元素数量达到极限,否则它的开销很小。
I threw this together. There might be a bit of overhead from doing an if and .length for every loop, but I think its minor unless the number of elements get extreme.
Array.prototype.slice.call() 在 IE 7 中失败,使用:
Array.prototype.slice.call() fails in IE 7, use this:
现在我肯定会使用以下版本:
Chrome、Firefox 3.5+、IE8+
IE11+、Firefox 24+、Chrome 30+(启用实验)
“element = elements[i]”优于“elements.length”,因为:
“节点列表通常被实现为带有过滤器的节点迭代器,这意味着获取像长度这样的属性是 O(n),并且通过重新检查长度来迭代列表将是 O(n^2)。
与数组访问不同,据我所知,数组访问的时间复杂度为 O(1)。
更多详细信息:
Nowadays I would definitely use the following:
Chrome, Firefox 3.5+, IE8+
IE11+, Firefox 24+, Chrome 30+ (with experiments enabled)
"element = elements[i]" is preferred over "elements.length" since:
"Node lists are often implemented as node iterators with a filter. This means that getting a property like length is O(n), and iterating over the list by re-checking the length will be O(n^2)."
Unlike array access, which is as far as I remember O(1).
More details:
首先,我认为可以使用 Array.prototype 连接数组,如下所示:
但它不起作用,因此我从节点集合创建了一个数组并将其连接起来。 看起来像这样:
First, I thought that this is possible to concat arrays using Array.prototype, like this:
But it doesn't work, so that I've made an arrays from node collections and concat it. Looks like that:
我的小书签的简短代码:
My short code for bookmarklets:
试试我的方法:
try my way: