dataset使用方法
Uncaught TypeError: Cannot read property ‘style’ of null at HTMLLIElement.lis..onclick (3.切换的导航栏.html:116)
// An highlighted block
<!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>
* {
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
.box {
width: 500px;
height: 600px;
margin: 50px auto;
background-color: #ccc;
border: 1px solid #222;
}
.title {
width: 100%;
height: 50px;
background-color: #ccc;
}
.title li {
float: left;
width: 25%;
height: 50px;
line-height: 50px;
text-align: center;
cursor: pointer;
}
.active {
background-color: white;
color: orange;
}
.content {
height: 550px;
width: 100%;
}
.content li {
height: 550px;
width: 100%;
display: none;
}
</style>
</head>
<body>
<div class="box">
<div class="title" style="border-bottom: 1px solid #222;">
<ul id=" ">
<li data-name="one " class="active">西部</li>
<li data-name="tow ">中部</li>
<li data-name="three ">得分</li>
<li data-name="four ">助攻榜</li>
</ul>
</div>
<div class="content ">
<ul id="navb_box ">
<li id="one " style="display: block; ">哈</li>
<li id="tow ">拉</li>
<li id="three ">打开</li>
<li id="four ">三等号</li>
</ul>
</div>
</div>
<script>
// var li = document.querySelector(".title li:nth-child(1) ");
// console.log(li)
// var c = li.classList.contains("active");
// console.log(c)
// var li = document.querySelector(".title li:nth-child(1) ");
// console.log(li);
// var li_name = li.dataset.name;
// console.log(li_name);
// 1.先对上面的头部导航栏进行设置
//-------1. 先获取标签
var lis = document.querySelectorAll(".title li ");
// 对获取的lis标签伪数组进行遍历
for (i = 0; i < lis.length; i++) {
lis[i].onclick = function() {
for (j = 0; j < lis.length; j++) {
lis[j].classList.remove("active");
}
this.classList.add("active");
// 当用户点击其中某个lis标签的时候,将其class值对应下面对应的id值
// ---------------1.首先获取对应的new_lis标签
var new_lis = document.querySelectorAll(".content li");
// 对得到的伪数组进行遍历
for (f = 0; f < new_lis.length; f++) {
// 排他思想,对所有的标签进行格式清除
new_lis[f].style.display = "none";
}
var newlis_ID = this.dataset.name;
console.log(this)
var daiti_lis = document.getElementById(newlis_ID);
// 对点击事件的盒子进行样式给与
daiti_lis.style.display = "block";
}
}
</script>
</body>
</html>
对dataset属性进行使用时,应注意dataset只能获取(data-自定义的名字),所以设置自定义属性是应该注意,比如命名为data-name时,应该注意是-中横线,而不是下横线。
而且注意display属性,写错的时候程序是不报错的,只会数据无法写入标签