jQuery--选择器(基本选择器、层次选择器)详解
jQuery选择器
通过jQuery选择器可以方便快捷地获得页面中的元素,然后为其添加相应行为,无需担心浏览器的兼容性问题。jQuery选择器完全继承了CSS选择的风格,将jQuery选择器分为4类:基本选择器、层次选择器、过滤选择器和表单选择器。
基本选择器
基本选择器是jQuery中最常用的选择器,通过元素的id、className或tagName来查找页面中的元素,如下表:
选择器 | 描述 | 返回 |
---|---|---|
#ID | 根据元素的ID进行匹配 | 单个jQuery对象 |
.class | 根据元素的class属性进行匹配 | jQuery对象数组 |
element | 根据元素的标签名进行匹配 | jQuery对象数组 |
selector1,selectot2,…,selectorN | 将每个选择器匹配的结果合并后一起返回 | jQuery对象数组 |
* | 匹配页面的所有元素,包括html、head、body等 | jQuery对象数组 |
示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery基本选择器</title>
<script type="text/javascript" src="js/jquery-2.1.0.js" ></script>
</head>
<body>
<div id="idDiv">idDIv</div>
<div class="classDiv" style="border: 1px;">classDiv</div>
<div class="classDiv">classDiv</div>
<span class="classSpan">classSpan</span>
<script type="text/javascript"> $(function(){ $("#idDiv").css("color","blue"); $(".classDiv").css("background-color", "#dddddd"); $("span").css("font-size", "40px"); $("#idDiv,.classSpan").css("font-style","italic"); }); </script>
</body>
</html>
层次选择器
jQuery层次选择器是通过DOM对象的层次关系来获取特定的元素,如同辈元素、后代元素、子元素和相邻元素等。层次选择器的用法与基本选择器相似,也是使用$()函数来实现,返回结果均为jQuery对象数组。
选择器 | 描述 | 返回 |
---|---|---|
$(“ancestor descendant”) | 选取ancestor元素中的所有的子元素 | jQuery对象数组 |
$(“parent > child”) | 选择parent元素中的直接子元素 | jQuery对象数组 |
$(“prev+next”) | 选取紧邻prev元素之后的next元素 | jQuery对象数组 |
$(“prev~siblings”) | 选取prev元素之后的siblings兄弟元素 | jQuery对象数组 |
示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery层次选择器</title>
<script type="text/javascript" src="js/jquery-2.1.0.js" ></script>
</head>
<body>
<div>
搜索条件<input name="search"/>
<form>
<label>用户名:</label>
<input name="userName" />
<fieldset>
<label>密 码:</label>
<input name="password" />
</fieldset>
</form>
<hr />
身份证号:<input name="none" /><br />
联系电话:<input naem="none"/>
</div>
<script type="text/javascript"> $(function(){ //form下的所有input $("form input").css("width","200px"); //form的直接子元素input $("form>input").css("background","pink"); //紧邻label的input $("label+input").css("border-color","blue"); //$("label").next("input").css("border-color","blue"); //form之后相邻的input $("form~input").css("border-bottom-width","5px"); //$("form").nextAll("input").css("border-bottom-width","4px"); $("*").css("padding-top","10px"); }); </script>
</body>
</html>
还没有评论,来说两句吧...