-1
我想使用JS对象(经典主题)构建DOM树。我完成了大部分的工作,但是我得到了一个无意义的结果:DOM树看起来是正确创建的,但是所有节点都在一行上变得平坦,并且输入元素被剪裁。如何获得适当的节点树渲染?
我高度怀疑buildNode
函数工作不正常,但我找不到该缺陷。
/**** FILTERS ****/
// TODO : change crappy filter using dictionnary
const attrOnly = (str) => !(str === 'content' || str === 'tag' || str === 'children');
/**** TESTS ****/
const hasChildren = (obj) => obj.hasOwnProperty('children'),
hasContent = (obj) => obj.hasOwnProperty('content');
// TODO: search for namespace given a tag name (SVG)
const findNameSpace = (str) => null;
// Build node with correct attributes and values
const buildNode = function (element, parent) {
const tag = (element.tag || 'div'),
tagAttr = Object.keys(element).filter(attrOnly),
node = document.createElementNS(findNameSpace(tag), tag);
tagAttr.forEach(
(attr) => node.setAttributeNS(findNameSpace(tag), attr, element[attr])
);
hasContent(element) ? node.innerHTML = element.content : null;
return parent.appendChild(node);
}
// Walk along the tree mapping current element with function f.
function walkTree(f, element, parent) {
const current = f(element, parent);
// Reccursively walk children, if necessary
(hasChildren(element) && element.children.forEach(
child => walkTree(f, child, current)
));
};
let tree = {
tag: 'div',
id: 'tree',
children: [{
tag: 'section',
id: 'section-l1-1',
class: 'l1',
content: 'Use <em>me</em> as I am, I am gorgeous!',
children: [{
tag: 'div',
id: 'div-l2',
class: 'l2',
children: [{
tag: 'p',
content: 'Here is a nested paragraph.'
}]
}, {
tag: 'form',
id: 'form-l2',
class: 'l2',
onsubmit: 'alert("Function called!");',
children: [{
tag: 'input',
type: 'text',
id: 'input-l3',
class: 'l3',
value: 'self-closing tag case!'
}]
}]
}, {
tag: 'footer',
id: 'end-page',
class: 'l1',
content: 'This is a running experiment.'
}]
};
walkTree(buildNode, tree, document.getElementById('seed'));
#seed div,form,input {
display: block;
}
<div id="seed"></div>
代码本身很好,你只需要声明一个新行或追加一行''
''当你去同样的效果。 – Crowes
我不需要任何'
'......我编辑了代码片段并添加了一些样式'display:block'。输入仍然隐藏。它看起来像所有的节点连接或什么。 – hsolatges
如果我使用开发人员工具手动编辑表单的节点,则会显示输入!多么疯狂的臭虫......! – hsolatges