next 是同輩不包含自己,而parent是自己的親生父母。
語法:.parent( [ selector ] )
介紹:取得一個匹配元素中,父元素的元素集合。
1)HTML片段
<h2>demo</h2>
<div class="demo">
<p>Hello word!</p>
<p>Hello word! 2</p>
</div>
<div class="demo">
<span>Hello word! 3</span>
</div>
<div class="demo">
<p>text</p>
<p>text2</p>
<p>text3</p>
</div>
2)JS片段
說明:在p元素中抓取p元素的父元素集合,因此抓取到包住p的div
<script type="text/javascript">
$(document).ready(function(){
$('p').parent().css('background', 'yellow');
});
</script>
3)完整程式碼
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('p').parent().css('background', 'yellow');
});
</script>
<style type="text/css">
.demo{
border:dotted #4040c2 1px;
width: 200px;
margin:5px;
}
</style>
</head>
<body>
<h2>demo</h2>
<div class="demo">
<p>Hello word!</p>
<p>Hello word! 2</p>
</div>
<div class="demo">
<span>Hello word! 3</span>
</div>
<div class="demo">
<p>text</p>
<p>text2</p>
<p>text3</p>
</div>
</body>
</html>
4)執行結果
沒有留言:
張貼留言