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