find()和children()方法都用于过滤匹配元素的子级,除了前者向下移动任何级别,后者向下移动单个级别。
要简单
- find() –搜索匹配元素的子级,孙级,曾孙级……任何级别的下级。
- children() –仅搜索匹配元素的子级(单级向下)。
请参见以下示例,以了解find()和children()的区别 。
jQuery find()vs children()示例
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
border:1px solid;
}
</style>
</head>
<body>
<h1>jQuery find() vs children() example</h1>
<script type="text/javascript">
$(document).ready(function(){
$("#testChildren").click(function () {
$('div').css('background','white');
$('.B1').children('.child').css('background','red');
});
$("#testFind").click(function () {
$('div').css('background','white');
$('.B1').find('.child').css('background','red');
});
});
</script>
</head><body>
<div class="B1">
<div class="child">B1-1</div>
<div class="child">B1-2</div>
<div class="orphan">B1-3 - Orphan</div>
<div class="child">B1-4</div>
<div class="B2">
<div class="child">B2-1</div>
<div class="child">B2-2</div>
<div class="orphan">B2-2 - Orphan</div>
<div class="B3">
<div class="child">B3-1</div>
<div class="orphan">B3-2 - Orphan</div>
<div class="child">B3-3</div>
</div>
</div>
</div>
<br/>
<br/>
<br/>
<input type='button' value='.B1 children(child)' id='testChildren'>
<input type='button' value='.B1 find(child)' id='testFind'>
</body>
</html>
翻译自: https://mkyong.com/jquery/difference-between-find-and-children-in-jquery/