点击,不同的tab_menu,显示不同的tab_box
注意点:
1.获取ul下,当前li的编号. $(‘div ul li’).index(this)
2.显示ul下编号为$index的li -> $(‘ul li’).eq($index)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.tab{
border:1px solid black;
border-radius: 10px;
padding: 15px;
width: 230px;
}
.hide{
display: none;
}
.selected{
background: #ffa
}
li{
display: inline-block;
border-left: 1px solid black;
padding: 5px;
}
li:hover{
cursor: pointer;
}
.tab_box{
padding: 5px;
border: 1px solid black;
border-radius: 5px;
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div class="tab">
<div class="tab_menu">
<ul>
<li class="selected">时事</li>
<li >体育</li>
<li >娱乐</li>
</ul>
</div>
<div class="tab_box">
<div>时事</div>
<div class="hide">体育</div>
<div class="hide">娱乐</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
$(function(){
$('div.tab_menu li').click(function(){
$(this)
.addClass('selected')
.siblings().removeClass("selected")
let $index = $('div.tab ul li').index(this)
$('div.tab_box >div')
.eq($index)
.show()
.siblings().hide()
})
})
</script>
</body>
</html>
参考《锋利的jQuery》(第2版)P166~P167