从JavaScript中的单个节点创建节点列表 [英] Create node list from a single node in JavaScript

查看:48
本文介绍了从JavaScript中的单个节点创建节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很简单,但是我无法提出一种很好的方法.

This is one of those it seems so simple, but I cannot come up with a good way to go about it.

我有一个节点,也许是 nodelist = document.getElementById("mydiv"); -我需要将其标准化为节点列表.也不是数组:一个真正的,真正的 nodeList 对象.

I have a node, maybe nodelist = document.getElementById("mydiv"); - I need to normalize this to a node list. And not an array either: an actual, bona-fide nodeList object.

nodelist = [document.getElementById("mydiv")];

请没有图书馆.

推荐答案

重现此问题,因为我最近想起了有关 JavaScript 的知识.这取决于 NodeList 的检查方式,但是..

Reviving this because I recently remembered something about JavaScript. This depends on how the NodeList is being checked, but..

var singleNode = (function () {
    // make an empty node list to inherit from
    var nodelist = document.createDocumentFragment().childNodes;
    // return a function to create object formed as desired
    return function (node) {
        return Object.create(nodelist, {
            '0': {value: node, enumerable: true},
            'length': {value: 1},
            'item': {
                "value": function (i) {
                    return this[+i || 0];
                }, 
                enumerable: true
            }
        }); // return an object pretending to be a NodeList
    };
}());

现在,如果您这样做

var list = singleNode(document.body); // for example

list instanceof NodeList; // true
list.constructor === NodeList; // true

list 具有属性 length 1 0 作为您的节点,以及从 NodeList .

and list has properties length 1 and 0 as your node, as well as anything inherited from NodeList.

如果您不能使用 Object.create ,则可以执行相同的操作,只是使用原型 nodelist 的构造函数并设置 this ['0']=节点; this ['length'] = 1; ,然后使用 new 创建.

If you can't use Object.create, you could do the same except as a constructor with prototype nodelist and set this['0'] = node;, this['length'] = 1; and create with new.

这篇关于从JavaScript中的单个节点创建节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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