wrapAll() 與 wrap() 名字很像,行為卻差很多:wrap() 是替每一個符合的元素各自套一層,而 wrapAll() 是把所有符合的元素「集中到一個」新的共同父元素裡。這個差異決定了它能用來做群組化排版。
$(selector).wrapAll(elem)
參數 elem 為用來包裹目標的 DOM 元素。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>wrapAll() 示範</title>
<style type="text/css">
div { width:200px; height:200px; border:1px solid blue; margin-top:10px; }
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").wrapAll(document.getElementById("content"));
});
});
</script>
</head>
<body>
<p>我是一個段落</p>
<p>我是一個段落</p>
<div id="content"></div>
<button>用 div 包裹所有段落</button>
</body>
</html>
$(selector).wrapAll(html)
參數 html 為用來包裹目標元素的 HTML 標記碼。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>wrapAll() 示範</title>
<style type="text/css">
.content { width:200px; height:200px; border:1px solid blue; }
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").wrapAll("<div class='content'></div>");
});
});
</script>
</head>
<body>
<p>這是一個段落</p>
<p>這是一個段落</p>
<button>用 div 包裹所有段落</button>
</body>
</html>
按下按鈕後,兩個 p 不會各自被包,而是被搬到同一個新 div 裡成為兄弟節點。這也意味著它們在文件中的位置會改變——原本被其他元素隔開的段落,會被拉到一起。若你的排版依賴原始 DOM 順序,使用前要先想清楚。
三個 wrap 家族方法的分工可以這樣記:wrap() 各自包一層、wrapAll() 全部包進一個、wrapInner() 只包內容不包元素本身。