当 HTML 作为参数传入时,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 中删除并在集合中返回给您。
彼得的一个例子: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() 与 replaceWith()
var html = $('#test_id p').html();
将返回“我的内容”
但 var replaceWith = $('#test_id p').replaceWith();
将返回 <p>My Content</p>
的整个 DOM 对象。
2.) html('value') 与 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()
也可能很有用。在下面显示的基准测试中,这更快,但前提是您需要多次调用此函数。
请参阅:https://jsperf.com/jquery-html-vs-empty-append-test