jquery .html() 与 .append()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3015335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery .html() vs .append()
提问by Argiropoulos Stavros
Lets say I have an empty div:
假设我有一个空的 div:
<div id='myDiv'></div>
Is this:
这是:
$('#myDiv').html("<div id='mySecondDiv'></div>");
The same as:
等同于:
var mySecondDiv=$("<div id='mySecondDiv'></div>");
$('#myDiv').append(mySecondDiv);
回答by James
Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
每当您将 HTML 字符串传递给任何 jQuery 方法时,都会发生以下情况:
A temporary element is created, let's call it x. x's innerHTML
is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes
) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes
as a fresh DOM collection.
创建了一个临时元素,我们称之为 x。x'sinnerHTML
设置为您传递的 HTML 字符串。然后 jQuery 会将每个生成的节点(即 x's childNodes
)转移到一个新创建的文档片段,然后将其缓存以备下次使用。然后它将片段childNodes
作为一个新的 DOM 集合返回。
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div>
to jQuery()
, jQuery will take a shortcut and simply do document.createElement('div')
.
请注意,它实际上比这复杂得多,因为 jQuery 进行了大量跨浏览器检查和各种其他优化。例如,如果您只传递<div></div>
给jQuery()
,jQuery 将走捷径并简单地执行document.createElement('div')
。
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, hereand here.
编辑:要查看 jQuery 执行的大量检查,请查看此处、此处和此处。
innerHTML
is generallythe faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ...
-- as I mentioned, there are a bunch of checks and optimisations occurring.
innerHTML
是一般的快的方法,虽然不要让支配你做什么,所有的时间。jQuery 的方法并不element.innerHTML = ...
像我提到的那样简单——正如我所提到的,需要进行大量检查和优化。
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
正确的技术在很大程度上取决于情况。如果你想创建大量相同的元素,那么你最不想做的就是创建一个巨大的循环,在每次迭代时创建一个新的 jQuery 对象。例如,使用 jQuery 创建 100 个 div 的最快方法:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
还需要考虑可读性和维护问题。
This:
这个:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lotharder to maintain than this:
......是很多难以维持比这个:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});
回答by Doug Neiner
They are not the same. The first one replacesthe HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appendsit to the first.
她们不一样。第一个替换HTML 而不先创建另一个 jQuery 对象。第二个为第二个 div 创建一个额外的 jQuery 包装器,然后将它附加到第一个。
One jQuery Wrapper(per example):
一个 jQuery 包装器(每个示例):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers(per example):
两个 jQuery 包装器(每个示例):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html
is a great call since its the equivalent of innerHTML = "..."
. However, if you just want to append content, the extra $()
wrapper set is unneeded.
您有几个不同的用例。如果你想替换内容,这.html
是一个很好的调用,因为它相当于innerHTML = "..."
. 但是,如果您只想附加内容,$()
则不需要额外的包装器集。
Only use two wrappers if you need to manipulate the added div
later on. Even in that case, you still might only need to use one:
如果您div
稍后需要操作添加的内容,则仅使用两个包装器。即使在这种情况下,您仍然可能只需要使用一个:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();
回答by mkoryak
if by .add
you mean .append
, then the result is the same if #myDiv
is empty.
如果.add
你的意思是.append
,那么结果是一样的,如果#myDiv
是空的。
is the performance the same? dont know.
性能一样吗?不知道。
.html(x)
ends up doing the same thing as .empty().append(x)
.html(x)
最终做同样的事情 .empty().append(x)
回答by Luca Matteis
回答by kizzx2
You can get the second method to achieve the same effect by:
您可以通过以下方式获得达到相同效果的第二种方法:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html()
just inserts hte HTML which results in faster performance.
Luca 提到html()
只插入 hte HTML 会导致更快的性能。
In some occassions though, you would opt for the second option, consider:
但在某些情况下,您会选择第二个选项,请考虑:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);
回答by Arianbakh
Other than the given answers, in the case that you have something like this:
除了给出的答案,如果你有这样的事情:
<div id="test">
<input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
var isAllowed = true;
function changed()
{
if (isAllowed)
{
var tmpHTML = $('#test').html();
tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').html(tmpHTML);
isAllowed = false;
}
}
</script>
meaning that you want to automatically add one more file upload if any files were uploaded, the mentioned code will not work, because after the file is uploaded, the first file-upload element will be recreated and therefore the uploaded file will be wiped from it. You should use .append() instead:
这意味着如果上传了任何文件,您想自动添加一个文件上传,上述代码将不起作用,因为上传文件后,将重新创建第一个文件上传元素,因此上传的文件将从中删除. 您应该使用 .append() 代替:
function changed()
{
if (isAllowed)
{
var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').append(tmpHTML);
isAllowed = false;
}
}
回答by daCoda
.html()
will replace everything.
.html()
将取代一切。
.append()
will just append at the end.
.append()
只会在最后追加。
回答by Binita Bharati
This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html
will end up adding only the last object to the parent element, whereas .append
will add all the list objects as children of the parent element.
这发生在我身上。jQuery 版本:3.3。如果您正在循环遍历对象列表,并希望将每个对象添加为某个父 dom 元素的子元素,那么 .html 和 .append 的行为就会大不相同。.html
最终只会将最后一个对象添加到父元素,而.append
会将所有列表对象添加为父元素的子元素。