Answers:
采取以下HTML代码:
<div id="mydiv">Hello World</div>
正在做:
$('#mydiv').html('Aloha World');
将导致:
<div id="mydiv">Aloha World</div>
正在做:
$('#mydiv').replaceWith('Aloha World');
将导致:
Aloha World
因此html()替换了元素的内容,而replaceWith()替换了实际的元素。
replaceWith()将替换当前元素,而html()仅替换内容。
请注意,replaceWith()实际上不会删除该元素,而只是将其从DOM中删除并在集合中返回给您。
彼得的示例:http : //jsbin.com/ofirip/2
-1
并希望这会对所有人有所帮助。:)
var $form = $target.closest('tr').replaceWith(html)
原来$form
包含了替换之前的元素。叹息
有两种使用html()和replaceWith()Jquery函数的方法。
<div id="test_id">
<p>My Content</p>
</div>
1.)html()vs replaceWith()
var html = $('#test_id p').html();
将返回“我的内容”
但是
var replaceWith = $('#test_id p').replaceWith();
会返回的整个DOM对象
<p>My Content</p>
。
2.)html('value')vs replaceWith('value')
$('#test_id p').html('<h1>H1 content</h1>');
将为您提供以下内容。
<div id="test_id">
<p><h1>H1 content</h1></p>
</div>
但是,
$('#test_id p').replaceWith('<h1>H1 content</h1>');
它将为您提供以下结果。
<div id="test_id">
<h1>H1 content</h1>
</div>
知道.empty().append()
也可以代替来使用也可能很有用.html()
。在下面显示的基准测试中,这样做速度更快,但前提是您需要多次调用此函数。