jquery add() 应用

一个运行代码演示用的站点:http://jsfiddle.net/

jquery  add()

<!DOCTYPE html>
<html>
<head>
<style>
div { width:60px; height:60px; margin:10px; float:left; }
p { clear:left; font-weight:bold; font-size:16px;
color:blue; margin:0 10px; padding:2px; }
</style>
<script type=”text/javascript” src=”http://shanmao.me/f/jquery.min.js”></script>
</head>
<body>
<div></div>

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

<p>Added this… (notice no border)</p>
<script>

$(“div”).css(“border”, “2px solid red”)
.add(“p”)
.css(“background”, “yellow”);
</script>

</body>
</html>

这里的add(“p”)相当于和的意思。
就是说$(“div”)的css和p的css

—————————

<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<p>Hello</p><span>Hello Again</span>
<script>$(“p”).add(“span”).css(“background”, “yellow”);</script>

</body>
</html>

p和span的css

————————-
<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<p>Hello</p>
<script>$(“p”).clone().add(“<span>Again</span>”).appendTo(document.body);</script>

</body>
</html>

clone()复制的意思;
复制一个p和把<span>Again</span>插入到文档的body中。

结果

Hello

Hello
Again

——————————–

<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<p>Hello</p><span id=”a”>Hello Again</span>
<script>var collection = $(“p”);
// capture the new collection
collection = collection.add(document.getElementById(“a”));
collection.css(“background”, “yellow”);</script>

</body>
</html>

选择p赋值给collection

collection和id=a的元素的css
这里用来一个id选择器document.getElementById(“a”)

———————————————