index.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
li{
list-style: none;
display: inline-block;
margin-right: 50px;
cursor: pointer;
}
ol li{
display: none;
}
</style>
<script src="../js/jquery-1.11.0.min.js"></script>
</head>
<body>
<ul>
<li>11</li>
<li>22</li>
<li>33</li>
</ul>
<ol>
<li style="display: block">哈哈哈</li>
<li>呵呵呵</li>
<li>哦哦哦</li>
</ol>
<script>
// 1.es6语法
// const btns = document.querySelectorAll('ul li')
// const lis = document.querySelectorAll('ol li')
// for (let i=0;i<btns.length;i++){
// btns[i].addEventListener('click',function () {
// console.log(i);
// for (let j=0;j<btns.length;j++){
// lis[j].style.display = 'none'
// }
// lis[i].style.display = 'block'
// })
// }
// 2.原生
// var btns = document.querySelectorAll('ul li')
// var lis = document.querySelectorAll('ol li')
// for (var i=0;i<btns.length;i++){
// btns[i].setAttribute('index',i)
// btns[i].addEventListener('click',function () {
// var index = this.getAttribute('index')
// console.log(index);
// for (var j=0;j<btns.length;j++){
// lis[j].style.display = 'none'
// }
// lis[index].style.display = 'block'
// })
// }
// 3.采用闭包
// var btns = document.querySelectorAll('ul li')
// var lis = document.querySelectorAll('ol li')
// for (var i=0;i<btns.length;i++){
// (function (i) {
// btns[i].addEventListener('click',function () {
// for (var j=0;j<btns.length;j++){
// lis[j].style.display = 'none'
// }
// lis[i].style.display = 'block'
// })
// })(i)
// }
// 4.jQuery实现
$(function () {
$('ul li').on('click',function () {
var index = $(this).index()
console.log(index);
$('ol li').eq(index).show().siblings().hide()
})
})
</script>
</body>
</html>
运行结果: