Home > Web Front-end > JS Tutorial > Detailed explanation of hierarchical selector usage examples in JQuery_jquery

Detailed explanation of hierarchical selector usage examples in JQuery_jquery

WBOY
Release: 2016-05-16 15:58:20
Original
1377 people have browsed it

The examples in this article describe the usage of hierarchical selectors in JQuery. Share it with everyone for your reference. The details are as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>层次选择器</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
 //------1.在给定的祖先元素下匹配所有后代元素
 //(包含了子元素,以及子元素的元素,一直往下延伸)
 var $divs = $("#main div");
 for (var i = 0; i < $divs.length; i++) {
 alert($divs.get(i).id);
 }
 //------2.在给定的父元素下匹配所有子元素,只包括直接子元素
 //(不包含子元素的子元素)
 var $divs = $("#main > div");
 for (var i = 0; i < $divs.length; i++) {
 alert($divs.get(i).id);
 }
 //-----3.prev + next $("lable + input ") : 匹配所有紧接在prev后的next元素
 //注意:只能去到第一个,并且是紧挨着的,如果不是紧挨着div1后面的则取不到
 //.....<1>.例子1
 var $divBrother = $("#div1 + div"); //用#div1 ID选择器 ,只取到div2
 alert($divBrother.get(0).id);
 //.....<2>.例子2
 var $divBrothers = $("div + div"); 
 //用div 标签选择器,相邻的div都能取到 divSun1(和divSun相邻),div2(和div1相邻)
 for (var i = 0; i < $divBrothers.length; i++) {
 alert($divBrothers.get(i).id);
 }
 //-----4.prev ~ siblins
 //$("form ~ input") : 匹配prev元素之后的所有siblings元素 
 //注意:在匹配之后的元素,不包含该元素在内,
 //并且siblings匹配的是和prev同辈的元素,其后辈元素不被匹配。
 var $divBrothers = $("#main ~ div");
 for (var i = 0; i < $divBrothers.length; i++) { //得到main1,main2,main3
 alert($divBrothers.get(i).id);
 }
 }
);
</script>
</head>
<body>
<div id="main">
 <div id="div1" class="myDiv">我是div1
 <div id="divSun">我是孙子div
  <div id="divSunSun">我是孙子的孙子div</div>
 </div>
 <div id="divSun1">我是孙子div</div>
 </div>
 <div id="div2" class="myDiv">我是div2</div>
</div>
<div id="main1"></div>
<div id="main2"></div>
<input type="button" value="button" />
<div id="main3"></div>
</body>
</html>
Copy after login

Readers who are interested in more content related to jquery selector can check out the special topic of this site: "Summary of jquery selector usage"

I hope this article will be helpful to everyone’s jQuery programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template