为了减少DOM操作的数量,我想生成一个临时DOM,稍后我将其添加到网页的DOM中。
在我的情况下,我想链接元素,即以
开头<span>.1.</span>
我想添加<span>.2.</span>
导致
<span>.1.</span><span>.2.</span>
是否可以在未定义根元素的情况下向另一个元素添加/追加元素?
我到目前为止找到的唯一方法是使用add()
并重新分配结果,但这是一个好习惯吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>TEMPLATE</title>
</head>
<body>
<div id="main">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
var mainRef = $('#main');
// Using add() and reassignment works (but I have to reassign,...)
var newElem1 = $('<div>foo</div>');
newElem1 = newElem1.add("<strong>.1.</strong>");
newElem1 = newElem1.add($("<strong>.2.</strong>"));
// append() works with root element (I don't want a root element)
var newElem2 = $('<div>');
newElem2.append("<strong>.3.</strong>");
newElem2.append($("<strong>.4.</strong>"));
// creating element directly works (but that's not adding)
var newElem3 = $('<div>.5.</div><div>.6.</div>');
// append() does not work with an empty root element
var newElem4 = $('');
newElem4.append("<strong>.7.</strong>");
newElem4.append($("<strong>.8.</strong>"));
mainRef.append(newElem1);
mainRef.append(newElem2);
mainRef.append(newElem3);
mainRef.append(newElem4);
});
</script>
</body>
</html>
答案 0 :(得分:3)
您似乎正在寻找一个documentFragment
,顾名思义它是一个文档的片段,并且存在暂时保存元素,直到您准备将该片段添加到文档本身;例如:
var fragment = document.createDocumentFragment(),
div = document.createElement('div');
// documentFragment not present in the DOM at this point:
fragment.appendChild(div);
// document fragment contains a child element,
// neither of which is present in the DOM.
// appending the document to the document:
document.body.appendChild(frag);
// the <div> is now in the DOM, the fragment
// itself is not, and no longer contains the <div>.
当fragment
仅附加到<body>
后,<div>
实际上已插入,fragment
不再存在。
答案 1 :(得分:1)
在learn.jquery.com上讨论了这个问题。解决方案:
这也适用于文本元素。试试例如:
$(function() {
var myItems = [];
var myList = $( "#main" );
for ( var i = 0; i < 10; i++ ) {
myItems.push( "<div>div-item " + i + "</div>" );
}
for ( var i = 0; i < 10; i++ ) {
myItems.push( "Text-item " + i + ", " );
}
myList.append( myItems.join( "" ) );
});