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

DMC*_*MCS 144 jquery

当HTML作为参数传入时,jQuery的replaceWith()和html()函数有什么区别?

Pao*_*ino 283

Take this HTML code:

<div id="mydiv">Hello World</div>
Run Code Online (Sandbox Code Playgroud)

Doing:

$('#mydiv').html('Aloha World');
Run Code Online (Sandbox Code Playgroud)

Will result in:

<div id="mydiv">Aloha World</div>
Run Code Online (Sandbox Code Playgroud)

Doing:

$('#mydiv').replaceWith('Aloha World');
Run Code Online (Sandbox Code Playgroud)

Will result in:

Aloha World
Run Code Online (Sandbox Code Playgroud)

So html() replaces the contents of the element, while replaceWith() replaces the actual element.


cgp*_*cgp 31

replaceWith() will replace the current element, whereas html() simply replaces the contents.

Note that the replaceWith() will not actually delete the element but simply remove it from the DOM and return it to you in the collection.

An example for Peter: http://jsbin.com/ofirip/2

  • +1写下来非常有用,即replaceWith()实际上并不删除该元素.我没想到这个! (3认同)
  • 这是真的,它仍然存在.它不在DOM中,所以你不会看到它,但它仍然是一个有效的HTML片段.证明:http://jsbin.com/ofirip/2 (2认同)
  • 是的,我现在已经打了至少半个小时了,我刚才意识到函数返回被替换的元素,我期待它返回一个像这样的代码:`var $ form = $ target.closest ('tr').replaceWith(html)`事实证明`$ form`包含替换前的元素.*叹* (2认同)

Har*_*sha 7

有两种使用 html() 和 replaceWith() Jquery 函数的方法。

<div id="test_id">
   <p>My Content</p>
</div>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

$('#test_id p').replaceWith('<h1>H1 content</h1>');会给你以下输出。

<div id="test_id">
      <h1>H1 content</h1>
</div>
Run Code Online (Sandbox Code Playgroud)