【发布时间】:2016-02-25 20:30:37
【问题描述】:
当 HTML 作为参数传入时,jQuery 的 replaceWith() 和 html() 函数有什么区别?
【问题讨论】:
-
这对我有帮助!我试图使用 jquery 动态更改标签的文本,这个线程肯定对我有帮助。谢谢!
标签: jquery
当 HTML 作为参数传入时,jQuery 的 replaceWith() 和 html() 函数有什么区别?
【问题讨论】:
标签: jquery
知道.empty().append() 也可以用来代替.html() 也可能很有用。在下面显示的基准测试中,这更快,但前提是您需要多次调用此函数。
【讨论】:
有两种方式使用 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(); 将返回整个 DOM 对象
<p>My Content</p>.
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>
【讨论】:
replaceWith() 将替换当前元素,而 html() 只是替换内容。
请注意,replaceWith() 不会真正删除元素,而只是将其从 DOM 中删除并在集合中返回给您。
【讨论】:
-1,希望这对所有人都有帮助。 :)
$form 包含替换前的元素。 叹息
老问题,但这可能对某人有所帮助。
如果您的 HTML 无效,这些函数在 Internet Explorer 和 Chrome / Firefox 中的运行方式会有所不同。
清理您的 HTML,它们将按文档说明工作。
(不关闭我的</center> 花了我一个晚上!)
【讨论】:
获取此 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() 替换了实际元素。
【讨论】: