jQuery的replaceWith()函数会用提供的内容替换匹配元素,而html()函数则用提供的内容替换匹配元素的内容。
请看这段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 中移除它并将其作为一个集合返回给您。
Peter 的示例:http://jsbin.com/ofirip/2
var $form = $target.closest('tr').replaceWith(html)
结果发现 $form
包含的是替换前的元素。叹气 - Pawel Krakowiak<div id="test_id">
<p>My Content</p>
</div>
1.) html() vs replaceWith()
var html = $('#test_id p').html();
将返回"My Content"
但是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>
虽然这个问题比较老,但是这个答案可能会对某些人有所帮助。
如果你的HTML不合法,在Internet Explorer和Chrome / Firefox中这些函数的操作方式会有所不同。
清理你的HTML,它们将按照文档中描述的方式工作。
(我没有关闭我的</center>
标签,导致我浪费了整个晚上!)
还有一个有用的提示是,.empty().append()
也可以代替.html()
。在下面展示的基准测试中,如果您需要多次调用此函数,则这种方法更快。