gpt4 book ai didi

javascript - 使用 JavaScript 将 HTML append 到 DOM

转载 作者:行者123 更新时间:2023-11-30 12:11:31 25 4
gpt4 key购买 nike

好的,我将使用以下 javascript 将 HTML 元素 append 到 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 标签中,因此非常感谢您的帮助。

最佳答案

您应该从 creating a DocumentFragment 开始然后您可以在将片段插入 DOM 之前将每个子元素 append 到该元素。

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 are DOM Nodes. They are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance.

关于javascript - 使用 JavaScript 将 HTML append 到 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33661443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com