首頁  >  文檔處理  > replaceWith(content|fn)

返回值:jQueryreplaceWith(content|fn)

jQuery replaceWith() 方法概述

將所有匹配的元素替換成指定的HTML或DOM元素。

參數(shù)

contentString, Element, jQuery, FunctionV1.2

用于將匹配元素替換掉的內(nèi)容。如果這里傳遞一個(gè)函數(shù)進(jìn)來的話,函數(shù)返回值必須是HTML字符串。

fnFunctionV1.4

返回THML字符串,用來替換的內(nèi)容。

示例

描述:

把所有的段落標(biāo)記替換成加粗的標(biāo)記。

HTML 代碼:
<p>Hello</p><p>cruel</p><p>World</p>
jQuery 代碼:
$("p").replaceWith("<b>Paragraph. </b>");
結(jié)果:
<b>Paragraph. </b><b>Paragraph. </b><b>Paragraph. </b>

描述:

用第一段替換第三段,你可以發(fā)現(xiàn)他是移動(dòng)到目標(biāo)位置來替換,而不是復(fù)制一份來替換。

HTML 代碼:
<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>
jQuery 代碼:
$('.third').replaceWith($('.first'));
結(jié)果:
<div class="container">
  <div class="inner second">And</div>
  <div class="inner first">Hello</div>
</div>