[英]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.