繁体   English   中英

将对象的属性或数组附加到节点的属性

[英]Attach object's properties or an array to a node's properties

我正在创建一个动态表单,其中包含许多不同的div。 每个div都有自己独特的输入组合。 我已经读到appendChild比更改innerHTML更快,因此我的解决方案是建立数组数量。 每个数组都是div格式,每个数组中定义了几个对象。 每个对象都是一个输入。

例如:

        var div = [
            label = {
                tag: "label",
                text: "Enter password",
                for: "pass"
            },
                input = {
                tag: "input",
                type: "password",
                name: "pass"
            }
        ];

最初,我使用foreach语句使用setAttribute这样将对象的属性附加到新元素上,如下所示:(同时将'tag'属性用作html标签,然后删除它,因此它不会显示为属性)。

for(var elem in div) {
    var temp = document.createElement(div[elem].tag);
    delete div[elem].tag;
    for(var prop in div[elem]) {
        temp.setAttribute(prop,input[prop]);
    }
    parentDiv.appendChild(temp);
}

问题是我想将更多东西添加到无法通过属性添加的元素中。 像:innerText。 所以也许我可以使该数组成为可以合并到“ temp”节点的属性数组?

提前致谢!

您可以像这样在for循环之前在其他部分中处理该问题

for(var elem in div) {
  var temp = document.createElement(div[elem].tag);
  delete div[elem].tag;

  // add the other properties
  ["innerHtml", "innerText"].forEach(function (attr) {
     if(div[ele][attr]) {
        temp[attr] = div[ele][attr]
        delete div[ele][attr];
  });

  // add the attributes
  for(var prop in div[elem]) {
     temp.setAttribute(prop.input[prop]);
  }
  parentDiv.appendChild(temp);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM