jQuery中find()方法用法实例

本文实例讲述了jQuery中find()方法用法。分享给大家供大家参考。具体分析如下:

此方法获得匹配元素集合中所有元素的子元素,并通过选择器、jQuery 对象或元素删选。
find()方法是获取匹配元素后代元素的好方法。

注意:children()只获取一级子元素,而find()将查找所所有子元素。

语法结构一:

$(selector).find(expr)

参数列表:

参数 描述
expr 字符串值,定义筛选表达式。

实例代码:


<!DOCTYPE html> 

<html> 

<head> 

<meta charset=" utf-8"> 

<meta name="author" content="https://www.nhooo.com/" /> 

<title>children()函数-呐喊教程</title> 

<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>

<script type="text/javascript"> 

$(document).ready(function(){ 

  $(".father").find("p").css("color","red"); 

}) 

</script>  

</head> 

<body> 

<div class="father"> 

<div class="children"> 

   <p>我是孙子p</p> 

</div> 

<p>我是儿子p</p> 

</div> 

<p>我是兄弟p</p> 

</body> 

</html>

以上代码可以将father元素下的所有p元素的字体颜色设置为红色。

语法结构二:

$(selector).find(element)

可以查找匹配元素下指定的元素。

参数列表:

参数 描述
element 用于匹配元素的DOM对象或者jQuery对象。

实例代码:


<!DOCTYPE html>

<html>

<head>

<meta charset=" utf-8">

<meta name="author" content="https://www.nhooo.com/" />

<title>find()函数-呐喊教程</title>

<style type="text/css">

.father{

  height:200px;

  width:200px;

  border:1px solid blue;

}

</style>

<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>

<script type="text/javascript">

$(document).ready(function(){

  $(".father").find(document.getElementById("myp")).css("border","1px solid red");

})

</script>

</head>

<body>

<div class="father">

  <div class="children">

    <p id="myp">我是孙子p</p>

  </div>

  <p>我是儿子p</p>

</div>

<p>我是兄弟p</p>

</body>

</html>

以上代码可以将father元素下id属性值为myp的元素的边框设置为一像素红色。

希望本文所述对大家的jQuery程序设计有所帮助。