jQuery 选择器的使用(2)
作者:无常 来源:无常的blog 时间:2008-01-21 13:07:00
支持的Axis选择器
Descendant Element has a descendant element
$("//div//p")
Child Element has a child element
$("//div/p")
Preceding Sibling Element has an element before it, on the same axes
$("//div ~ form")
Parent Selects the parent element of the element
$("//div/../p")
支持的谓词
[@*] 拥有一个属性
$("//div[@*]")[@foo] 拥有foo属性
$("//input[@checked]")[@foo='test'] 属性foo值为'test'
$("//a[@ref='nofollow']")[Nodelist] Element contains a node list, for example:
$("//div[p]")
$("//div[p/a]")
支持的谓词,但与XPath和CSS又不同的
[last()] or [position()=last()]改为:last
$("p:last")[0] or [position()=0] 改为 :eq(0) or :first
$("p:first")
$("p:eq(0)")[position() < 5] 改为:lt(5)
$("p:lt(5)")[position() > 2] 改为:gt(2)
$("p:gt(2)")
定制的选择器
jQuery包含一些在CSS和XPath都不用到的表达式,但我们觉得它们使用起来非常方便,所以包含进来了。
下列的列表式语法基于不同的CSS选择器,但又有非常相似的名字。
:even 从匹配的元素集中取序数为偶数的元素
:odd 从匹配的元素集中取序数为奇数的元素
:eq(0) and :nth(0) 从匹配的元素集中取第0个元素
:gt(4) 从匹配的元素集中取序数大于N的元素
:lt(4) 从匹配的元素集中取序数小于N的元素
:first 相当于 :eq(0)
:last 最后一个匹配的元素
:parent 选择包含子元素(包含text节点)的所有元素
:contains('test') 选择所有含有指定文本的元素
:visible 选择所有可见的元素(display值为block 或者visible 、visibility 值为visible的元素,不包括hide域)
:hidden 选择所有隐藏的元素(非Hide域,且display值为block 或者visible 、visibility 值为visible的元素)
例:
$("p:first").css("fontWeight","bold");$("div:hidden").show();$("div:contains('test')").hide();
表单选择器
这是为表单提供的一些选择器:
:input 选择表单元素(input, select, textarea, button)
:text 选择所有文本域(type="text")
:password 选择所有密码域(type="password").
:radio 选择所有单选按钮(type="radio").
:checkbox 选择所有复选框(type="checkbox").
:submit 选择所有提交按钮(type="submit").
:image 选择所有图像域 (type="image").
:reset 选择所有清除域(type="reset").
:button 选择所有按钮(type="button").
同样也可以使用:hidden,详细说明上面已经介绍过。
$('#myForm :input')
如果你需要指定表单:
$('input:radio', myForm)
这将选择myForm表单中所有单选按钮。选择radio通常是用[@type=radio],但是这样用理精简些。
更多的选择器
jQuery选择器可以用一些第三方部件进行扩充:
Patch to allow selection by CSS property (full plugin to be released simultaneously with 1.1)
无常翻译:http://wuchang.cnblogs.com
原文:"http://www.docs.jquery.com/DOM/Traversing/Selectors"