本文實例講述了jQuery中closest()函數(shù)用法。分享給大家供大家參考。具體分析如下:
此函數(shù)從元素本身開始,逐級向上級元素匹配,并返回最先匹配的元素。
closest()函數(shù)會首先檢查當前元素是否匹配,如果匹配則直接返回元素本身。如果不匹配則向上查找父元素,一層一層往上,直到找到匹配選擇器的元素。如果什么都沒找到則返回一個空的jQuery對象。
語法結(jié)構(gòu)一:
$(selector).closest(expr, context)
參數(shù)列表:
| 參數(shù) | 描述 |
| expr | 用以過濾元素的表達式 |
| context | 可選。作為待查找的 DOM 元素集或者文檔。 |
實例代碼:
實例一:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://m.survivalescaperooms.com/" />
<title>closest()函數(shù)-武林網(wǎng)</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".father p").closest("div").css("color","green");
})
</script>
</head>
<body>
<div class="father">
<div class="children"> 我是div
<p>我是孫子p</p>
</div>
<p>我是兒子p</p>
</div>
<p>我是兄弟p</p>
</body>
</html>
實例二:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://m.survivalescaperooms.com/" />
<title>closest()函數(shù)-武林網(wǎng)</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#children p").closest("#father",document.getElementById("children")).
css("border","1px solid red");
})
</script>
</head>
<body>
<div id="father">
<div id="children">
<p>我是孫子p</p>
</div>
<p>我是兒子p</p>
</div>
<p>我是兄弟p</p>
</body>
</html>
由于id為father的div并沒有在id為children的div之內(nèi),所以并不能將其邊框設(shè)置為紅色。
語法結(jié)構(gòu)二:
$(selector).closest(element)
參數(shù)列表:
| 參數(shù) | 描述 |
| element | 用于匹配元素的DOM元素或者jQuery元素。 |
實例代碼:
實例一:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://m.survivalescaperooms.com/" />
<title>closest()函數(shù)-武林網(wǎng)</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#children p").closest(document.getElementById("children")).
css("border","1px solid red");
})
</script>
</head>
<body>
<div id="father">
<div id="children">
<p>我是孫子p</p>
</div>
<p>我是兒子p</p>
</div>
<p>我是兄弟p</p>
</body>
</html>
實例二:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://m.survivalescaperooms.com/" />
<title>closest()函數(shù)-武林網(wǎng)</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#children p").closest($("#children")).css("border","1px solid red");
})
</script>
</head>
<body>
<div id="father">
<div id="children">
<p>我是孫子p</p>
</div>
<p>我是兒子p</p>
</div>
<p>我是兄弟p</p>
</body>
</html>
希望本文所述對大家的jQuery程序設(shè)計有所幫助。