jQuery的强大选择器小结

  作者:bea

一 基本选择器 $("input“) :选择所有是input标签的元素 $("#input1"):选择id为input1的元素 $(".acss"):选择所有包含acss 这个css类样式的 代码 代码如下: <body> <a href="">link</a> <input id="input1" class="acss"> <input id="Text1" class="acss"> <in
一 基本选择器
$("input“) :选择所有是input标签的元素
$("#input1"):选择id为input1的元素
$(".acss"):选择所有包含acss 这个css类样式的
代码


代码如下:


<body>
<a href="">link</a>
<input id="input1" class="acss">
<input id="Text1" class="acss">
<input id="Text2" >
<script>
var oo = $("input"); //oo是以上3个的集合
var pp = $("#input1");//pp是第一个
var qq = $(".acss");//qq 是前两个的集合
</script>
</body>


可以用以上3个尽兴组合式的查询
var ww = $("input.acss"); //选择具有acss的input标签元素
var ee = $("input#Text1.acss");//选择具有acss 的 id为 Text1的 标签为input的元素

二、子选择器
父节点和直接子节点用(>)隔开,即实现子选择器方式


代码如下:


<p class="acss">
<a href="" id="a1"></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
</p>
<p>
<a href="" id="a2"></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
<a href=""></a>
</p>
<script>
var oo = $("p a "); //选择了p下面的所有的a
var pp = $("p>a"); //选择了2个a元素 ,id为a1 和a2
var qq = $("p.acss a"); //选择了id为a1的元素
</script>



三、特征选择器
根据元素特征进行选择 a[href^=http://]
代码


代码如下:


<div>
<input id="Text3" name="myInput" />
<input id="Text5" name="myput" />
<input id="Text4" name="yourInput" />
<a id="a3" href="http://www.baidu.com"></a>
<a id="a4" href="www.baidu.com"></a>
</div>
<script>
var oo = $("a[href^=http://]"); //选择href以 http:// 开头的a。a3选中
var pp = $("input[name$=Input]"); //选择name以 Input 结尾的input 。Text3,Text4选中
var qq = $("a[href*=com]"); //选择href以 包含com的a 。a3,a4选中
var ww = $("input[id=Text3]"); //选择正好等于的
</script>


另外 jQuery还提供了 has方法,如上面例子中
div:has(input) 含义是。选择包含input的所有div
注意: div input 是选择的是div中的所有input 元素

四、位置选择器
位置选择器主要是根据元素的位置进行选择,
div a:first 返回页面第一个在div中的a
div a last 返回页面最后一个在div中的a
div odd 返回页面偶数位置的div
div even 返回页面奇数位置的idv
div first-child 返回div 中第一个子选择
div last-child 返回div 中最后一个子选择
only-child 没有兄弟节点的元素
nth-child(n):第n个子节点
eq(n) 第n个匹配元素
gt(n) n之后的匹配元素 不包含
lt(n) n之前的匹配元素 不包含

五、jQuery自定义选择




名称
说明
解释


:input
匹配所有 input, textarea, select 和 button 元素
查找所有的input元素: $(":input")


:text
匹配所有的文本框
查找所有文本框: $(":text")


:password
匹配所有密码框
查找所有密码框: $(":password")


:radio
匹配所有单选按钮
查找所有单选按钮


:checkbox
匹配所有复选框
查找所有复选框: $(":checkbox")


:submit
匹配所有提交按钮
查找所有提交按钮: $(":submit")


:image
匹配所有图像域
匹配所有图像域: $(":image")


:reset
匹配所有重置按钮
查找所有重置按钮: $(":reset")


:button
匹配所有按钮
查找所有按钮: $(":button")


:file
匹配所有文件域
查找所有文件域: $(":file")







名称
说明
解释


:enabled
匹配所有可用元素
查找所有可用的input元素: $("input:enabled")


:disabled
匹配所有不可用元素
查找所有不可用的input元素: $("input:disabled")


:checked
匹配所有选中的被选中元素(复选框、单选框等,不包括select中的option)
查找所有选中的复选框元素: $("input:checked")


:selected
匹配所有选中的option元素
查找所有选中的选项元素: $("select option:selected")






有用  |  无用

猜你喜欢