Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 实现一个类似于数据ID的系统_Javascript_Html - Fatal编程技术网

Javascript 实现一个类似于数据ID的系统

Javascript 实现一个类似于数据ID的系统,javascript,html,Javascript,Html,我正在实现一个类似于DataReactID的系统(从头开始)。类似这样的内容:(与使用数据reactid的目的不完全相同): 到 我能够创建一个解析HTML的JSON对象,但无法以更简单的方式完成我想要的事情,请您帮助我,用同样的方式 function mapDOM(element, json) { var treeObject = {}; // If string convert to document Node if (typeof elemen

我正在实现一个类似于DataReactID的系统(从头开始)。类似这样的内容:(与使用数据reactid的目的不完全相同):



我能够创建一个解析HTML的JSON对象,但无法以更简单的方式完成我想要的事情,请您帮助我,用同样的方式

function mapDOM(element, json) {
    var treeObject = {};

    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        } 
        element = docNode.firstChild;
    }

    //Recursively loop through DOM elements and assign properties to object
    var li=lj=lk=-1;
    function treeHTML(element, object) {
        ++li;
        object["type"] = element.nodeName;
        var nodeList = element.childNodes;
        if (nodeList != null) {
            if (nodeList.length) {
                object["content"] = [];
                for (var i = 0; i < nodeList.length; i++) {
                    ++lj;
                    if (nodeList[i].nodeType == 3) {
                        object["content"].push(nodeList[i].nodeValue);
                    } else {
                        object["content"].push({});
                        treeHTML(nodeList[i], object["content"][object["content"].length -1]);
                    }
                    document.getElementsByTagName(nodeList[i])[i].setAttribute("data-reactid","0."+i+"."+li+"."+lj);
                }
            }
        }
        if (element.attributes != null) {
            if (element.attributes.length) {
                object["attributes"] = {};
                for (var i = 0; i < element.attributes.length; i++) {
                    object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
                }
            }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}
函数mapDOM(元素,json){
var treeObject={};
//如果字符串转换为文档节点
if(元素类型==“字符串”){
if(window.DOMParser){
parser=新的DOMParser();
docNode=parser.parseFromString(元素,“text/xml”);
}否则{//微软又罢工了
docNode=newActiveXObject(“Microsoft.XMLDOM”);
docNode.async=false;
loadXML(元素);
} 
元素=docNode.firstChild;
}
//递归地循环DOM元素并为对象分配属性
var li=lj=lk=-1;
函数树HTML(元素、对象){
++李,;
对象[“类型”]=element.nodeName;
var nodeList=element.childNodes;
if(节点列表!=null){
if(节点列表长度){
对象[“内容”]=[];
对于(变量i=0;i
像那样吗

function processNode(node, id) {
    id = !id ? "0" : String(id);
    node.dataset.id = id;
    return {
        id: id,
        type: node.nodeName.toLowerCase(),
        content: processNodeList( node.childNodes, id + "." ),
        attributes: processAttributes( node.attributes )
    }
}

function processNodeList(nodes, prefix){
    prefix = !prefix ? "" : String(prefix);

    for(var out, i=0, j=0, len = (nodes && nodes.length)|0; i < len; ++i){
        var node = nodes[i], nt = node.nodeType;
        if(nt === 1){ //Element
            value = processNode(node, prefix + j++);
        }else if(nt === 3){ //Text-Node
            //especially &nbsp; should be kept, and not replaced on stringify
            var text = node.textContent.replace(/[\u00A0<>&\u00AD]/g, toHtmlEntity);

            /*
            //TODO: move that into a filter, applied when the Array is built
            //remove all-whitespace-nodes between two block-nodes like p,div,section,h1-h6
            if((i === 0 || i === nodes.length-1) && /^[\r\n\t ]*$/.test(text)){
                //remove whitespace at the beginning or the end of the node
                continue;
            }
            */

            //compact multiple spaces into a single one
            value = text.replace(/([\r\n\t ])+/g, "$1");
        }else{
            continue;
        }

        out || (out = []);
        out.push(value);
    }
    return out;
}

function processAttributes(attrs){
    for(var out, i = 0, len = (attrs && attrs.length)|0; i < len; ++i){
        var attr = attrs[i];
        if(attr.nodeName === "data-id") continue;
        out || (out = {});
        out[attr.nodeName] = attr.nodeValue;
    }
    return out;
}

function toHtmlEntity(c){
    switch(c.charCodeAt(0)){
        case 160: return "&nbsp;";
        case 38: return "&amp;";
        case 60: return "&lt;";
        case 62: return "&gt;";
        case 173: return "&shy;";
    }
    return c;
}

function mapDOM(element) {
    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        }
        element = docNode.firstChild;
    }

    return processNode(element);
}


var tree = mapDOM(document.body);
console.log(JSON.stringify(tree, null, 4));
函数processNode(节点,id){
id=!id?“0”:字符串(id);
node.dataset.id=id;
返回{
id:id,
类型:node.nodeName.toLowerCase(),
内容:processNodeList(node.childNodes,id+”),
属性:processAttributes(node.attributes)
}
}
函数processNodeList(节点,前缀){
前缀=!前缀?“:字符串(前缀);
对于(var out,i=0,j=0,len=(nodes&&nodes.length)|0;i
function mapDOM(element, json) {
    var treeObject = {};

    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        } 
        element = docNode.firstChild;
    }

    //Recursively loop through DOM elements and assign properties to object
    var li=lj=lk=-1;
    function treeHTML(element, object) {
        ++li;
        object["type"] = element.nodeName;
        var nodeList = element.childNodes;
        if (nodeList != null) {
            if (nodeList.length) {
                object["content"] = [];
                for (var i = 0; i < nodeList.length; i++) {
                    ++lj;
                    if (nodeList[i].nodeType == 3) {
                        object["content"].push(nodeList[i].nodeValue);
                    } else {
                        object["content"].push({});
                        treeHTML(nodeList[i], object["content"][object["content"].length -1]);
                    }
                    document.getElementsByTagName(nodeList[i])[i].setAttribute("data-reactid","0."+i+"."+li+"."+lj);
                }
            }
        }
        if (element.attributes != null) {
            if (element.attributes.length) {
                object["attributes"] = {};
                for (var i = 0; i < element.attributes.length; i++) {
                    object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
                }
            }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}
function processNode(node, id) {
    id = !id ? "0" : String(id);
    node.dataset.id = id;
    return {
        id: id,
        type: node.nodeName.toLowerCase(),
        content: processNodeList( node.childNodes, id + "." ),
        attributes: processAttributes( node.attributes )
    }
}

function processNodeList(nodes, prefix){
    prefix = !prefix ? "" : String(prefix);

    for(var out, i=0, j=0, len = (nodes && nodes.length)|0; i < len; ++i){
        var node = nodes[i], nt = node.nodeType;
        if(nt === 1){ //Element
            value = processNode(node, prefix + j++);
        }else if(nt === 3){ //Text-Node
            //especially &nbsp; should be kept, and not replaced on stringify
            var text = node.textContent.replace(/[\u00A0<>&\u00AD]/g, toHtmlEntity);

            /*
            //TODO: move that into a filter, applied when the Array is built
            //remove all-whitespace-nodes between two block-nodes like p,div,section,h1-h6
            if((i === 0 || i === nodes.length-1) && /^[\r\n\t ]*$/.test(text)){
                //remove whitespace at the beginning or the end of the node
                continue;
            }
            */

            //compact multiple spaces into a single one
            value = text.replace(/([\r\n\t ])+/g, "$1");
        }else{
            continue;
        }

        out || (out = []);
        out.push(value);
    }
    return out;
}

function processAttributes(attrs){
    for(var out, i = 0, len = (attrs && attrs.length)|0; i < len; ++i){
        var attr = attrs[i];
        if(attr.nodeName === "data-id") continue;
        out || (out = {});
        out[attr.nodeName] = attr.nodeValue;
    }
    return out;
}

function toHtmlEntity(c){
    switch(c.charCodeAt(0)){
        case 160: return "&nbsp;";
        case 38: return "&amp;";
        case 60: return "&lt;";
        case 62: return "&gt;";
        case 173: return "&shy;";
    }
    return c;
}

function mapDOM(element) {
    // If string convert to document Node
    if (typeof element === "string") {
        if (window.DOMParser) {
              parser = new DOMParser();
              docNode = parser.parseFromString(element,"text/xml");
        } else { // Microsoft strikes again
              docNode = new ActiveXObject("Microsoft.XMLDOM");
              docNode.async = false;
              docNode.loadXML(element); 
        }
        element = docNode.firstChild;
    }

    return processNode(element);
}


var tree = mapDOM(document.body);
console.log(JSON.stringify(tree, null, 4));