.replaceWith()
.replaceWith( newContent ) 返回:jQuery
描述:用提供的內(nèi)容替換所有匹配的元素。
-
version added: 1.2.replaceWith( newContent )
newContent用來插入的內(nèi)容,可能是HTML字符串,DOM元素,或者jQuery對象。
-
version added: 1.4.replaceWith( function )
function返回THML字符串,用來替換的內(nèi)容。
.replaceWith()可以從DOM中移除內(nèi)容,然后在這個地方插入新的內(nèi)容。請看下面的例子:
<div class="container"> <div class="inner first">Hello</div> <div class="inner second">And</div> <div class="inner third">Goodbye</div> </div>
我們可以用指定的HTML替換第二個 inner <div> :
$('.second').replaceWith('<h2>New heading</h2>');
結(jié)果如下:
<div class="container"> <div class="inner first">Hello</div> <h2>New heading</h2> <div class="inner third">Goodbye</div> </div>
同樣我們也可以一次性替換或有inner<div>:
$('.inner').replaceWith('<h2>New heading</h2>');
結(jié)果如下:
<div class="container"> <h2>New heading</h2> <h2>New heading</h2> <h2>New heading</h2> </div>
或者我們可以選擇一個元素把它當(dāng)做替換的內(nèi)容:
$('.third').replaceWith($('.first'));
結(jié)果如下:
<div class="container"> <div class="inner second">And</div> <div class="inner first">Hello</div> </div>
從這個例子中,我們可以看出用選中的元素替換目標(biāo)是移動而不是復(fù)制。
.replaceWith()方法,和大部分其他jQuery方法一樣,返回jQuery對象,所以可以喝其他方法鏈接使用,但是需要注意的是:返回的jQuery對象是和被移走的元素相關(guān)聯(lián),而不是新插入的元素。/p>
在jQuery 1.4中 .replaceWith(), .before(), 和.after()都對分離的DOM元素有效。請看下面的例子:
$("<div>").replaceWith("<p></p>");
.replaceWith()返回一個包含div的jQuery對象。
例子:
例子:點擊按鈕,用包含同樣文字的div替換按鈕:
<!DOCTYPE html>
<html>
<head>
<style>
button { display:block; margin:3px; color:red; width:200px; }
div { color:red; border:2px solid blue; width:200px;
margin:3px; text-align:center; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<button>First</button>
<button>Second</button>
<button>Third</button>
<script>
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
</script>
</body>
</html>
Demo:
例子:用粗體字替換所有段落。
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>$("p").replaceWith("<b>Paragraph. </b>");</script>
</body>
</html>
Demo:
例子:用空的div替換所有段落。
<!DOCTYPE html>
<html>
<head>
<style>
div { border:2px solid blue; margin:3px; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>$("p").replaceWith(document.createElement("div"));</script>
</body>
</html>
Demo:
例子:點擊,用DOM中現(xiàn)存的div元素替換每個段落。注意是移動而不是復(fù)制。
<!DOCTYPE html>
<html>
<head>
<style>
div { border:2px solid blue; color:red; margin:3px; }
p { border:2px solid red; color:blue; margin:3px; cursor:pointer; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div>Replaced!</div>
<script>
$("p").click(function () {
$(this).replaceWith($("div"));
});
</script>
</body>
</html>