2 回答

TA贡献1111条经验 获得超0个赞
问题是
element.append(create(o.innerHtml, element));
但create不返回任何内容,因此undefined附加到每个元素的末尾。改为刚刚
create(o.innerHtml, element)
反而:
const struct = [{
tag: 'div',
classes: ['container'],
innerHtml: [{
tag: 'input',
classes: ['input'],
attributes: [
['type', 'text'],
['placeholder', 'Some input']
]
},
{
tag: 'div',
classes: ['btn-block'],
innerHtml: [{
tag: 'div',
classes: ['btn', 'btn-long'],
innerText: 'Long Button'
},
{
tag: 'div',
classes: ['btn', 'btn-big', 'btn-img'],
innerHtml: [{
tag: 'img',
attributes: [
['src', 'https://www.w3schools.com/images/w3certified_logo_250.png']
],
}]
}
]
},
{
tag: 'div',
classes: ['red']
}
]
}];
const root = document.body;
function create(obj, root) {
obj.forEach(o => {
const element = document.createElement(o.tag);
if (o.classes) {
const classes = o.classes;
element.classList.add(...classes);
}
if (o.attributes) {
o.attributes.forEach(a => {
element.setAttribute(a[0], a[1]);
})
}
if (o.hasOwnProperty('innerHtml')) {
create(o.innerHtml, element)
}
if (o.innerText) {
element.innerText = o.innerText
}
if (element !== undefined) {
root.append(element);
}
});
}
create(struct, root);
.container {
padding: 5px;
border: 1px solid black;
display: flex;
justify-content: space-around;
align-items: center;
}
.input {
height: 20px;
width: 200px;
}
.btn-block {
display: flex;
justify-content: space-around;
align-items: center;
}
.btn {
border: 1px solid black;
border-radius: 5px;
padding: 5px 15px;
text-align: center;
}
.btn:hover {
cursor: pointer;
}
.btn-long {
width: 300px;
margin-right: 10px;
}
.red {
background: red;
height: 100px;
width: 100px;
}

TA贡献1784条经验 获得超8个赞
你只需要
create(o.innerHtml, element);
没有包装element.append(/* ... */);,因为你的函数不返回东西。
function create(obj, root) {
obj.forEach(o => {
const element = document.createElement(o.tag);
if (o.classes) {
const classes = o.classes;
element.classList.add(...classes);
}
if (o.attributes) {
o.attributes.forEach(a => {
element.setAttribute(a[0], a[1]);
})
}
if (o.hasOwnProperty('innerHtml')) {
create(o.innerHtml, element);
//element.append();
}
if (o.innerText) {
element.innerText = o.innerText
}
root.append(element);
});
}
const struct = [{
tag: 'div',
classes: ['container'],
innerHtml: [{
tag: 'input',
classes: ['input'],
attributes: [
['type', 'text'],
['placeholder', 'Some input']
]
},
{
tag: 'div',
classes: ['btn-block'],
innerHtml: [{
tag: 'div',
classes: ['btn', 'btn-long'],
innerText: 'Long Button'
},
{
tag: 'div',
classes: ['btn', 'btn-big', 'btn-img'],
innerHtml: [{
tag: 'img',
attributes: [
['src', 'https://www.w3schools.com/images/w3certified_logo_250.png']
],
}],
}
]
},
{
tag: 'div',
classes: ['red']
}
]
}];
const root = document.body;
create(struct, root);
添加回答
举报