[英]Attach object's properties or an array to a node's properties
I am creating a dynamic form with many different divs inside. 我正在创建一个动态表单,其中包含许多不同的div。 Each div has its own unique input combination. 每个div都有自己独特的输入组合。 I have read that appendChild is faster than changing the innerHTML so my solution is to build number of arrays. 我已经读到appendChild比更改innerHTML更快,因此我的解决方案是建立数组数量。 Each array is a div in the form and in each array there are several objects defined. 每个数组都是div格式,每个数组中定义了几个对象。 Each object is an input. 每个对象都是一个输入。
eg: 例如:
var div = [
label = {
tag: "label",
text: "Enter password",
for: "pass"
},
input = {
tag: "input",
type: "password",
name: "pass"
}
];
At first, I used a foreach statement to attach the object's property onto a new element using setAttribute like so: (while using a 'tag' property as the html tag and than deleting it so it will not appear as an attribute). 最初,我使用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);
}
The problem is I have more things I would like to add to the element that cannot be added thru attributes. 问题是我想将更多东西添加到无法通过属性添加的元素中。 Like: innerText. 像:innerText。 So maybe I could make the array an array of properties that I can merge into the 'temp' node? 所以也许我可以使该数组成为可以合并到“ temp”节点的属性数组?
Thanks in advance! 提前致谢!
You could just handle that in a different section just before the for loop like this 您可以像这样在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.