jQuery的replaceWith()和html()有什么区别?


145

将HTML作为参数传递时,jQuery的replaceWith()和html()函数之间有什么区别?


2
这帮助了我!我试图使用jquery动态更改标签的文本,该线程肯定对我有所帮助。谢谢!
HereToLearn_ 2015年

Answers:


289

采取以下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()替换了实际的元素。


1
很好的解释!
Luis Gouveia

31

replaceWith()将替换当前元素,而html()仅替换内容。

请注意,replaceWith()实际上不会删除该元素,而只是将其从DOM中删除并在集合中返回给您。

彼得的示例:http : //jsbin.com/ofirip/2


3
+1非常有用,可以将其记录下来,replaceWith()实际上并未删除元素。我还没有弄清楚!
彼得

2
是的,它仍然存在。它不在DOM中,因此您不会看到它,但是它仍然是有效的HTML。证明:jsbin.com/ofirip/2
cgp 2012年

1
是的,这是真的。感谢您提出的例子。从我的角度来看,我一直在考虑将其从DOM(加上垃圾回收)中删除,实际上是将其删除。但是您在技术上是正确的。我将删除,-1并希望这会对所有人有所帮助。:)
彼得

1
感谢您的说明,replaceWith()返回旧元素只是给了我一些调试上的挫败感:(
dain 2012年

2
是的,我已经为此奋斗了至少半个小时,我才意识到该函数返回了replaced元素,我希望它返回带有如下代码的新元素: var $form = $target.closest('tr').replaceWith(html) 原来$form包含了替换之前的元素。叹息
Pawel Krakowiak

5

有两种使用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>

2

旧问题,但这可能会帮助某人。

如果您的HTML无效,则这些功能在Internet Explorer和Chrome / Firefox中的运行方式会有一些差异。

清理您的HTML,它们将按记录工作。

</center>我晚上没关我的门!)


6
这就是为什么您不应该再使用center的原因。:p
罗曼部落

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.