码迷,mamicode.com
首页 > Web开发 > 详细

JQuery获取子孩子和兄弟元素的方法

时间:2015-03-08 11:50:43      阅读:14373      评论:0      收藏:0      [点我收藏+]

标签:jquery   选择器   子元素   兄弟元素   

这里说的获取当前元素的子孩子和兄弟元素的方法,另外还有遍历和指定的具体要求:

01.html代码:

<!DOCTYPE html>
<html>
	<head>
	<title>测试jquery</title>
		<meta charset="utf-8"/>
		<link rel="stylesheet" type="text/css" href="01.css"/>
		<script type="text/javascript" src="../test1/JQuery/jquery.js"></script>
		<script type="text/javascript" src="01.js"></script>
	</head>
	<body>
		<input type="button" value="测试1" id="button_1">
		<input type="button" value="测试2" id="button_2"><br/>
		<div id="div1" class="div_1">
			This is div1
		</div>
		<div id="div2" class="div_2">
			This is div_2
			<div id="div_2_1" class="div_2_1">
				This id div2_1
			</div>
			<div id="div2_2" class="div_2_2">
				This id div2_2
			</div>
			<div id="div2_3" class="div_2_3">
				This id div2_3
			</div>
		</div>
		<div id="div3" class="div_3">
			This is div_3
		</div>
	</body>
</html>
01.css

body{
	background-color: #efefef;
}
.div_1,.div_2,.div_2_1,.div_2_2,.div_2_3,.div_3{
	position: absolute;
}
.div_1{
	width: 200px;
	height: 200px;
	background-color: red;
}

.div_2{
	width: 300px;
	height: 700px;
	background-color: yellow;
	margin-left: 250px;
}
.div_2_1{
	width: 200px;
	height: 200px;
	background-color: black;
	margin: 10px 0px 0px 50px;
}
.div_2_2{
	width: 200px;
	height: 200px;
	background-color: green;
	margin: 220px 0px 0px 50px;
}
.div_2_3{
	width: 200px;
	height: 200px;
	background-color: blue;
	margin: 430px 0px 0px 50px;
}
.div_3{
	width: 200px;
	height: 200px;
	background-color: white;
	margin: 0px 0px 0px 600px;
}
利用外部js文件的方式来处理如下:

01.js

$(document).ready(function(){
	$("#button_1").click(function(){
		//所谓的子孩子就是当前元素的子代
		$('.div_2').children().each(function(){
			window.alert($(this).text());
		});
		//下面是指定第几个子孩子
		//alert($(".div_2").children().eq(0).text());
	});
	$("#button_2").click(function(){
	//同辈元素的获取
		//$('.div_1').nextAll().each(function(){
			//window.alert($(this).text());
			alert($(".div_2").nextAll().eq(0).text());
	});
	$("#button_3").click(function(){
		//获取div_1前面的所有的兄弟元素
		/*$(".div_3").prevAll().each(function(){
			alert($(this).text());
		});
		*/
		//获取.div的前面的第几个元素的内容
		alert($(".div_2").prev().eq(0).text());
	});
	$("#button_4").click(function(){
		$(".div_1").siblings().each(function(){
			alert($(this).text());
		});
	});
});

以上是关于获取子元素和兄弟元素的具体方法,仅供参考



JQuery获取子孩子和兄弟元素的方法

标签:jquery   选择器   子元素   兄弟元素   

原文地址:http://blog.csdn.net/mycodedream/article/details/44131543

(2)
(3)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!