好的,我用下面的javascript将HTML元素附加到DOM中。
$h.each(domNodes, function(domNode) {
var input;
input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('id', 'image-file');
input.setAttribute('name', 'files[]');
input.style.display = 'none';
domNode.addEventListener('click', function(){
input.style.opacity = 0;
input.style.display='block';
input.focus();
input.click();
input.style.display='none';
}, false);
domNode.appendChild(input);
}
}这会创建一行HTML,看起来像这样。
<input type="file" id="image-file" name="files[]" multiple="multiple" style="display: none;" />如果要创建如下所示的HTML输出,javascript会是什么样子的……
<input type="file" name="files[]" id="image-file" multiple />
<label class="file-button" for="image-file" >
<img src="img/upload.png" alt="add"> Upload Your File(s)
</label>我不确定如何使用纯javascript将HTML标签嵌套在其他HTML标签中,因此任何帮助都将不胜感激。
发布于 2015-11-12 07:10:14
应该从creating a DocumentFragment开始,然后在将片段插入到DOM之前,可以将每个子元素附加到该元素之后。
var docFragment = document.createDocumentFragment();
var input = document.createElement("input");
var label = document.createElement("label");
var img = document.createElement("img");
docFragment.appendChild(input);
docFragment.appendChild(label);
label.appendChild(img);
var form = document.getElementsByTagName("form")[0];
form.appendChild(docFragment);DocumentFragments是DOM节点。它们从来都不是主DOM树的一部分。通常的用例是创建文档片段,将元素附加到文档片段,然后将文档片段附加到DOM树。在DOM树中,文档片段被它的所有子片段替换。
由于文档片段在内存中,并且不是主DOM树的一部分,因此向其追加子级不会导致页面回流(计算元素的位置和几何形状)。因此,使用文档片段通常会带来更好的性能。
发布于 2015-11-12 07:07:27
作为没有任何内容的dom节点的各个元素的构造不会改变。通过使用appendChild和createTextNode方法组装各个零件,如下所示:
var input, img, label, text;
input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('id', 'image-file');
input.setAttribute('name', 'files[]');
input.setAttribute('multiple', 'multiple');
label = document.createElement('img');
label.setAttribute('class', 'file-button');
label.setAttribute('for', 'image-file');
img = document.createElement('img');
img.setAttribute('src', 'img/upload.png');
img.setAttribute('alt', 'add');
text = document.createTextNode(' Upload Your File(s)');
label.appendChild(img);
label.appendChild(text);
domNode.appendChild(input);
domNode.appendChild(label);笔记
如果您想要为新的DOM部分使用documentFragment容器,请参阅Dave Anderson的答案。
-
var htmlfrag = $(
'<input type="file" name="files[]" id="image-file" multiple />\n'
+ '<label class="file-button" for="image-file" >\n'
+ ' <img src="img/upload.png" alt="add"> Upload Your File(s)\n'
+ '</label>\n'
);
与$函数相比,$.parseHtml()可能更可取,因为它保留了字符串
(后两个方面的表扬给了Dave Anderson)
发布于 2015-11-12 07:06:31
与上面的操作相同,只是在将标签附加到domNode之前,必须将img元素附加到标签元素
https://stackoverflow.com/questions/33661443
复制相似问题