您的位置:首页 > Web前端 > JQuery

jQuery选择器

2016-06-18 15:23 477 查看

前言

本文内容摘自《锋利的jQuery》,梳理了jQuery里面的几种选择器的用法,这里只给出一个大概的结构,具体用法还请查资料


正文

jQuery选择器完全继承了CSS选择器的风格,可以随意将选择器组合在一起,下面来看看它支持哪些写法吧


常用选择器

标签选择器: $(“td”)

ID选择器: $(“#note”)

类选择器 : $(“.note”)

群组选择器:$(“td,#note, .note”)

后代选择器: $(“td input”) $(“td > input”)

通配符选择器: $(“*”) 、 $(“select *”) 、 $(“#note *”)

选择器可以组合使用,例如标签、Id、后代组合:$(“td#note span”)

层次选择器

选取ancestor所有后代: $(“ancestor descendant”)

选取parent元素子元素: $(“parent > child”)

prev元素下个同辈元素: $(“prev + next”)

prev之后所有兄弟节点: $(“prev~siblings”)

最后两个选择器注意和jQuery函数nextAll()、prevAll()、siblings()区分或者代替

过滤选择器

:first

:last

:not

:even

:odd

:eq

:gt

:lt

:header

:animated

:focus

上面的选择器其实也可以和之前的常用选择器、层次选择器混合使用,代表不同的含义。例如select:first 与select :first 一个表示相同类型下的第一个元素,而另一个表示这个类型下元素的第一个子元素;当然组合还有很多种方式:var name = $(“select > option:first”).val();

<body>
<select name="review">
<option value="0">苹果</option>
<option value="1">香蕉</option>
<option value="2">荔枝</option>
<option value="3">芒果</option>
</select>
<select class="retrieve">
<option value="3">芒果</option>
<option value="2">荔枝</option>
<option value="1">香蕉</option>
<option value="0">苹果</option>
</select>
<script>
$(function(){
var name = $("select:first").attr("name")
alert(name);
var val = $("select.retrieve :first").val();
alert(val);

})
</script>
</body>


内容过滤选择器

:contains

:empty

:has

:parent

可见性过滤选择器

:hidden

:visible

属性过滤选择器

[attribute] 例:$(“div[id]”)

[attribute=value] 例: $(“div[name=’test’]”)

[attribute!=value]

[attribute^=value] 注:以value开头

[attribute$=value] 注:以value结束

[attribute*=value]

[attribute|=value]

[attribute~=value]

[attribute1][attribute2][attributeN] 注:合并成复合属性熟悉器,范围每选择一次,缩小一次

这里用一个select的例子来说明

<body>
<select name="review">
<option value="0">苹果</option>
<option value="1" selected="selected">香蕉</option>
<option value="2">荔枝</option>
<option value="3">芒果</option>
</select>

<script>
var text = $("select[name='review'] option[selected]").text();
alert(text); //输出香蕉
</script>
</body>


子元素过滤选择器

:first-child

:last-child

:only-child

:nth-child

nth-child可以使用n这个字母,组成任意表达式,如2n 、2n+1 ,n会从1开始将满足条件的元素选取

表单对象属性过滤选择器

:enabled

:disabled

:checked

:selected

selected这个选择器,我想用select来举个例子

<body>
<select name="review">
<option value="0">苹果</option>
<option value="1" selected="selected">香蕉</option>
<option value="2">荔枝</option>
<option value="3">芒果</option>
</select>

<script>
var text =  $("select[name='review'] option:selected").text();
alert(text); //输出香蕉
</script>
</body>


表单选择器

:input

:text

:password

:radio

:checkbox

:submit

:image

:reset

:button

:file

:hidden

例子

<body>
<input type="radio" name="test" value="0" /> 一级
<input type="radio" name="test" checked value="1"/> 二级
<script>
var val = $("input:radio:checked").val();
alert(val); //输出1
</script>
</body>


结束语

jQuery非常的强大,还有很多优秀的开源,搬砖越来越容易了&_&
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery