jQuery的元素选取:
描述 示例 返回 根据给定的id匹配一个元素 $(#test)选取id为test的元素 单个元素 根据给定的类名匹配元素 $(".test")选取所有class为test的元素 集合元素 根据给定的元素名匹配元素 $("p")选取所有的<p>元素 集合元素 匹配所有元素 $("*")选取所有的元素 集合元素
以下是根据id匹配元素的一个例子
<html>
<head>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//下面存在两个同id名的元素,由于根据id名只能返回一个元素,所以jQuery会默认取一个
alert($("#test1").html());
});
</script>
</head>
<body>
<a id="test1" href="http://www.google.com">google</a>
<a id="test1" href="http://www.yahoo.com">yahoo</a>
</body>
</html>
以下是根据类名匹配元素的例子
<html>
<head>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//会弹出2
alert($(".test").length);
});
</script>
</head>
<body>
<a class="test" href="http://www.google.com">google</a>
<a class="test" href="http://www.yahoo.com">yahoo</a>
</body>
</html>
层次选择器:以下是四个层次选择器
选择器:$("ancestor descendant")
描述:选取ancestor元素里的所有descendant(后代)元素
返回:集合元素
示例:$("div span")选取<div>里的所有的<span>元素
选择器:$("parent>child")
描述:选取parent元素下的child(子)元素,与$("ancestor descendant")有区别,$("ancestor descendant")取
的是所有后代元素
返回:集合元素
示例:$("div>span")选取<div>元素下元素名是<span>的子元素
选择器:$('prev+next')
描述:选取紧接在prev元素后的next元素
返回:集合元素
示例:$('.one+div')选取class为one的下一个<div>元素
注意:此选择器可以用next方法代替,如$('.one').next('div')
选择器:$('prev~siblings')
描述:选取prev元素之后的所有siblings(兄弟)元素
返回:集合元素
示例:$('#two~div')选取id为two的元素后面的所有<div>兄弟元素,即平级的元素
注意:此选择器可以用nextAll方法代替,如$('#two').nextAll('div')
此外还有一个siblings'方法,它将返回所有前后的兄弟节点,如$('#two').nextAll('div'),上面的方法只返回之
后的兄弟节点。
过滤选择器: