在循环上附加HTML元素

时间:2019-02-22 13:06:31

标签: javascript recursion dom

给出这样的JSON结构:

Response.Write("<script>")
Response.Write("window.open('CRPage.aspx')")
Response.Write("</script>")

我正在尝试对其进行迭代,以将值转换为HTML标签。使用上面的JSON,我希望构造这个:

[
"Hi, ",
  {
    "tag": "a",
    "attr": {
      "href": "https://example.com",
      "target": "_blank"
    },
    "body": [
      "click ",
      {
        "tag": "strong",
        "body": [
          "here "
        ]
      }
    ]
  },
  "to get ",
  {
    "tag": "em",
    "body": [
      "amazing "
    ]
  },
  "offers."
]  

所以我将这个JSON传递给了像这样的递归函数:

<span>Hi, </span><a href="https://google.com" target="_blank">click <strong>here</strong></a>to get <em>amazing </em><span>offers.</span>

buildElement是一种方便的方法,可用于创建节点,设置属性并追加任何文本节点:

 stringHtmlText(content) {
   let result = content.map(tranche => {
        if (typeof tranche === "object") {
            let attrs = [];
            for (let attr in tranche.attr) {
                if (tranche.attr.hasOwnProperty(attr)) {
                    let thisAttr = {};
                    thisAttr[attr] = tranche.attr[attr];
                    attrs.push(thisAttr);
                }
            }

            return tranche.body.map(entry => {
                if (typeof entry === "object") {
                    let childNode = this.stringHtmlText([entry]);
                    if(Array.isArray(childNode)) {
                        childNode = childNode[0];
                    }
                    let parentNode = this.buildElement(tranche.tag, attrs, '');
//THIS IS THE OFFENDING LINE
                    parentNode.appendChild(childNode);
                    return parentNode;
                } else {
                    return this.buildElement(tranche.tag, attrs, entry);

                }
            })[0];

        } else {
            return this.buildElement('span', [], tranche);
        }

    });
    return result;
}

我遇到的问题是,即使在调试时我看到“强”节点被传递给parentNode.appendChild(childNode),当返回值时,parentNode“ a”标记没有子“ strong”,给我这样的结果:

 buildElement(tag, attributes, value = '') {
        let node = document.createElement(tag);
        if (value) {
            let text = document.createTextNode(value);
            node.appendChild(text);
        }
        if (attributes.length === 0) {
            return node;
        }
        return this.setAttributes(node, attributes);
    }

显然“ a”标签中缺少“ strong”标签。为什么节点未附加到父节点?

1 个答案:

答案 0 :(得分:0)

看起来像是问题在于,在主体中同时存在纯文本和附加节点的情况下,第二个映射函数实际上是在生成两个节点。

由于第一次迭代仅包含文本节点,因此获得第二次完整迭代的方法是将映射结果传递给变量,然后返回数组中的最后一个索引,如下所示:

 stringHtmlText(content) {
    {
        return content.map(tranche => {
            if (typeof tranche === "object") {
                let attrs = [];
                for (let attr in tranche.attr) {
                    if (tranche.attr.hasOwnProperty(attr)) {
                        let thisAttr = {};
                        thisAttr[attr] = tranche.attr[attr];
                        attrs.push(thisAttr);
                    }
                }
                let parentNode;
//Assign to variable
                let trancher = tranche.body.map(entry => {
                    if (typeof entry === "object") {
                        let childNode = this.stringHtmlText([entry]);
                        if (Array.isArray(childNode)) {
                            childNode = childNode[0];
                        }
                        parentNode.appendChild(childNode);
                        return parentNode;
                    } else {
                        parentNode = this.buildElement(tranche.tag, attrs, entry);
                        return parentNode;
                    }
                });
// Return only the last, complete node

                return trancher[(trancher.length - 1)]

            } else {
                return this.buildElement('span', [], tranche);
            }

        });
    }
}