.wrapAll()


.wrapAll( wrappingElement )返回: jQuery

描述: 在集合中所有匹配元素的外面包裹一个HTML结构。

  • 添加的版本: 1.2.wrapAll( wrappingElement )

    • wrappingElement
      类型: SelectorhtmlStringElementjQuery
      一个选择器,元素,HTML字符串,或jQuery对象指定的html结构环绕包裹的匹配元素。
  • version added: 1.4.wrapAll( function )

    • function
      类型: Function() => StringjQuery
      一个回调函数,返回的HTML内容或jQuery对象将包裹所有匹配的元素。函数内的this指向集合中的第一个元素。在jQuery 3.0 之前,回调函数错误地调用集合中的每一个元素并且接收所述集合中这个元素的索引位置作为参数。

.wrapAll()函数可以接受任何字符串或对象,可以传递给$()工厂函数来指定一个DOM结构。这种结构可以嵌套多层,但是最内层只能有一个元素。所有匹配元素将会被当作是一个整体,在这个整体的外部用指定的 HTML 结构进行包裹。

考虑下面的HTML:

1
2
3
4
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>

如果我们对inner元素用.wrapAll():

1
$('.inner').wrapAll('<div class="new" />');

new <div>元素是动态创建并添加到DOM中。 其结果是new <div>包裹了所有匹配的元素:

1
2
3
4
5
6
<div class="container">
<div class="new">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
</div>

例子:

Example: 在所有段落外包上新的div:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
<style>
div { border: 2px solid blue; }
p { background:yellow; margin:4px; }
</style>
<script src="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>$("p").wrapAll("<div></div>");</script>
</body>
</html>

Demo:

Example: 为 span 标签包裹一个对象树。注意,任何 span 之间的元素都不会被包裹,例如例子中使用的 <strong> (红色文本)。即使是 span 之间的空格也不会被包裹。可以查看原始 HTML 的源代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!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="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span>Span Text</span>
<strong>What about me?</strong>
<span>Another One</span>
<script>$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");</script>
</body>
</html>

Demo:

Example: 用一个 div 将所有的段落包裹起来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
<style>
div { border: 2px solid blue; }
p { background:yellow; margin:4px; }
</style>
<script src="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>$("p").wrapAll(document.createElement("div"));</script>
</body>
</html>

Demo:

Example: 使用一个嵌套深度为两层 div 的 jQuery 对象来包裹所有的段落。注意,这并不会移动用于包裹的对象,只是将克隆后的对象用于包裹。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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="//code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div class="doublediv"><div></div></div>
<script>$("p").wrapAll($(".doublediv"));</script>
</body>
</html>

Demo: