本文為大家介紹下在每個匹配元素的外部插入新元素的方法,下面有個不錯的示例,感興趣的朋友可以參考下
一、方法 wrap :把所有匹配的元素,用其他元素的結構化包裹起來 wrapAll : 把所有匹配的元素,用單個元素包裹起來 wrapInner : 把匹配元素的子類用html結構包裹起來 二、實例 (1)wrap 代碼如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="../jquery-2.0.0/jquery-2.0.0.js"></script> <script type="text/javascript"> $(function() { $("div a").wrap("<div id='id'></div>"); }); </script> </head> <body> <div> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> </div> </body> </html> firebug顯示結果: 代碼如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="../jquery-2.0.0/jquery-2.0.0.js" type="text/javascript"> <script type="text/javascript"> </head> <body> <div> <div id="id"> <a>liuxingyu</a> </div> <div id="id"> <a>liuxingyu</a> </div> <div id="id"> <a>liuxingyu</a> </div> <div id="id"> <a>liuxingyu</a> </div> </div> </body> </html> (2)wrapAll 代碼如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="../jquery-2.0.0/jquery-2.0.0.js"></script> <script type="text/javascript"> $(function() { $("div a").wrapAll("<div id='id'></div>"); }); </script> </head> <body> <div> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> </div> </body> </html> firebug顯示結果: 代碼如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="../jquery-2.0.0/jquery-2.0.0.js" type="text/javascript"> <script type="text/javascript"> $(function() { $("div a").wrapAll("<div id='id'></div>"); }); </script> </head> <body> <div> <div id="id"> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> </div> </div> </body> </html> (3)wrapInner 代碼如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="../jquery-2.0.0/jquery-2.0.0.js" type="text/javascript"> <script type="text/javascript"> $(function() { $("div").wrapInner("<div id='id'></div>"); }); </script> </head> <body> <div> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> </div> </body> </html> firebug顯示結果: 代碼如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="../jquery-2.0.0/jquery-2.0.0.js" type="text/javascript"> <script type="text/javascript"> $(function() { $("div").wrapInner("<div id='id'></div>"); }); </script> </head> <body> <div> <div id="id"> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> <a>liuxingyu</a> </div> </div> </body> </html>