在jquery中,你可以使用find()函数来搜索匹配元素标签的所有后代标签。
例如,div标签有三层,
<divid="A1">
<divclass="child">A1-1</div>
<divclass="child">A1-2</div>
<divid="A2">
<divclass="child">A2-1</div>
<divclass="child">A2-2</div>
<divid="A3">
<divclass="child">A3-1</div>
<divclass="child">A3-2</div>
</div>
</div>
</div>
1 $(‘#A1’).find(‘.child’)
$(‘#A1’).find(‘.child’).css(‘background’,’red’);
查找id为A1的标签,下所有class类为.child的后代。把其背景颜色改为红色。
2. $(‘#A2′).find(‘.child’)
$('#A2').find('.child').css('background','red');
与上类似。
具体代码:
<html>
<head>
<script type="text/javascript" src="../jquery-1.11.1.min.js"></script>
<style type="text/css">
div{
padding:8px;
border:1px solid;
}
</style>
</head>
<body>
<h1>jquery find() example</h1>
<script type="text/javascript">
$(document).ready(function(){
$('#button1').click(function(){
$('div').css('background','white');
$('#A1').find('.child').css('background','red');
});
$('#button2').click(function(){
$('div').css('background','white');
$('#A2').find('.child').css('background','red');
});
$('#button3').click(function(){
$('div').css('background','white');
$('#A3').find('.child').css('background','red');
});
});
</script>
<div id="A1">A1
<div class="child">A1-1</div>
<div class="child">A1-2</div>
<div id="A2">A2
<div class="child">A2-1</div>
<div class="child">A2-2</div>
<div id="A3">A3
<div class="child">A3-1</div>
<div class="child">A3-2</div>
</div>
</div>
</div>
<br/>
<br/>
<br/>
<input type='button' value='find #A1' id='button1'>
<input type='button' value='find #A2' id='button2'>
<input type='button' value='find #A3' id='button3'>
</body>
</html>
效果:
点击按钮1:
点击按钮2:
点击 按钮3: