程序:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
div{
width:600px;
height:130px;
border:5px solid red;
}
p{
width:100px;
height:100px;
background: pink;
float: left;
margin-right:10px;
}
</style>
<body>
<div class="box1">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<div class="box2">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<script src="js/jquery-1.12.3.min.js"></script>
<script>
// 点.box1的p,对应的.box2的p变颜色
$('.box1 p').click(function(){
console.log( $(this).index() ); //被点击p的index。只是亲兄弟之间的index,不关选择器怎么选择。
$('.box2 p').eq( $(this).index()).css("background","red");
});
</script>
</body>
</html>
运行结果:
程序二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
div {
width: 600px;
height: 200px;
border: 1px solid red;
}
p {
width: 100px;
height: 100px;
background: pink;
float: left;
margin-right: 10px;
}
</style>
<body>
<div class="box1">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<div class="box2">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<script src="js/jquery-1.12.3.min.js"></script>
<script>
// 两种方式给同一个p设置背景色
$("p").eq(5).css("background","red"); //所有的p中下标为5
$(" .box2 p").eq(1).css("background","red"); //.box2里的p下标为1
//输出的是.box1里的p在亲兄弟之间的索引,
// 当点击.box2里的p的时候不会有输出(前提是没有下列p的点击事件)
// $(".box1 p").click(function(){
// console.log( $(this).index() );
// })
//输出的是.box1里的p在亲兄弟之间的索引,.box2里的p在亲兄弟之间的索引
$("p").click(function(){
console.log( $(this).index() );
})
</script>
</body>
</html>
运行结果: