<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .tab_hd { display: flex; } li { margin: 20px; } .tab_bd li { display: none; } .active { color: red; } .show { display: block !important; } </style> </head> <body> <ul class="tab_hd"> <li class="active">关注</li> <li>推荐</li> <Li>热门</Li> </ul> <ul class="tab_bd"> <li class="show">关注了个啥</li> <li>推荐了和啥</li> <li>啥事热门</li> </ul> <script> var ohdli = document.querySelectorAll('.tab_hd li') console.log(ohdli) var obdli = document.querySelectorAll('.tab_bd li') for (var j = 0; j < ohdli.length; j++) { ohdli[j].setAttribute('index', j) //j不能打引号 ohdli[j].onclick = function () { for (var i = 0; i < ohdli.length; i++) { ohdli[i].classList.remove('active') } this.classList.add('active') for (var i = 0; i < obdli.length; i++) { obdli[i].classList.remove('show') } var x = this.getAttribute('index') //ohdli[j] 这个不能写 因为j永远是4 obdli[x].classList.add('show') } } </script> </body> </html>