首页 > 代码库 > API - .add()

API - .add()

jQuery的 .add 很像一个collection, 官方的这个demo很形象的表达了这个意思。

 1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>add demo</title> 6 <script src="http://code.jquery.com/jquery-1.10.2.js"></script> 7 </head> 8 <body> 9 <p>Hello</p>10 <span id="a">Hello Again</span>11 <script>12 var collection = $( "p" );13 // Capture the new collection14 collection = collection.add( document.getElementById( "a" ) );15 collection.css( "background", "yellow" );16 </script>17 </body>18 </html>

虽然像collection, 但注意下面的不同:

var pdiv = $("p");pdiv.add("div")pdiv.css("background-color", "green" );上面的代码, 只p背景色变为绿, div的背景色不变。改为下面这样,div的背景色才会也变成绿色。var pdiv = $("p");pdiv = pdiv.add("div")pdiv.css("background-color", "green" );

这种“断链”的问题同样表现在下面的demo中,(jQuery官网中的Examples中)

 1 <!doctype html> 2  3 <html lang="en"> 4  5 <head> 6  7   <meta charset="utf-8"> 8  9   <title>add demo</title>10 11   <style>12 13   div {14 15     width: 60px;16 17     height: 60px;18 19     margin: 10px;20 21     float: left;22 23   }24 25   p {26 27     clear: left;28 29     font-weight: bold;30 31     font-size: 16px;32 33     color: blue;34 35     margin: 0 10px;36 37     padding: 2px;38 39   }40 41   </style>42 43   <script src="http://code.jquery.com/jquery-1.10.2.js"></script>44 45 </head>46 47 <body>48 49  50 51 <div></div>52 53 <div></div>54 55 <div></div>56 57 <div></div>58 59 <div></div>60 61 <div></div>62 63  64 65 <p>Added this... (notice no border)</p>66 67  68 69 <script>70 71 $( "div" ).css( "border", "2px solid red" )72 73   .add( "p" )74 75   .css( "background", "yellow" );76 77 </script>78 79  80 81 </body>82 83 </html>

 

API - .add()