.wrap()
.wrap( wrappingElement ) 返回:jQuery
描述:在每個匹配的元素外層包上一個html元素。
-
version added: 1.0.wrap( wrappingElement )
wrappingElement一個HTML片段,選擇表達(dá)式,jQuery對象,或者DOM元素,用來包在匹配元素的外層。
-
version added: 1.4.wrap( wrappingFunction )
wrappingFunction一個生成用來包元素的回調(diào)函數(shù)。
參數(shù)可以是string或者對象只要能形成DOM結(jié)構(gòu),可以是嵌套的,但是結(jié)構(gòu)只包含一個最里層元素。這個結(jié)構(gòu)會包在每個匹配元素外層。該方法返回沒被包裹過的元素的jQuery對象用來鏈接其他函數(shù)。
例如:
<div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
用.wrap(),我們可以在inner <div>外層插入一個HTML結(jié)構(gòu)。
$('.inner').wrap('<div class="new" />');
結(jié)果如下:
<div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div>
該方法的第二種用法允許我們用函數(shù)做參數(shù),改函數(shù)返回一個DOM元素,jQuery對象,或者HTML片段,用來包住匹配元素。例如:
$('.inner').wrap(function() {
return '<div class="' + $(this).text() + '" />';
});
結(jié)果:
<div class="container">
<div class="Hello">
<div class="inner">Hello</div>
</div>
<div class="Goodbye">
<div class="inner">Goodbye</div>
</div>
</div>
例子:
例子:在所有段落外包一個div
<!DOCTYPE html>
<html>
<head>
<style>
div { border: 2px solid blue; }
p { background:yellow; margin:4px; }
</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").wrap("<div></div>");</script>
</body>
</html>
Demo:
例子:在span外層包一個對象樹。
<!DOCTYPE html>
<html>
<head>
<style>
div { border:2px blue solid; margin:2px; padding:2px; }
p { background:yellow; margin:2px; padding:2px; }
strong { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<span>Span Text</span>
<strong>What about me?</strong>
<span>Another One</span>
<script>$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");</script>
</body>
</html>
Demo:
例子:在所有段落外包上新建的div
<!DOCTYPE html>
<html>
<head>
<style>
div { border: 2px solid blue; }
p { background:yellow; margin:4px; }
</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").wrap(document.createElement("div"));</script>
</body>
</html>
Demo:
例子:在所有段落外包一個2層的jquery對象。注意元素不是移動而是復(fù)制到目標(biāo)位置。
<!DOCTYPE html>
<html>
<head>
<style>
div { border: 2px solid blue; margin:2px; padding:2px; }
.doublediv { border-color:red; }
p { background:yellow; margin:4px; font-size:14px; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div class="doublediv"><div></div></div>
<script>$("p").wrap($(".doublediv"));</script>
</body>
</html>