首页 新闻 赞助 找找看

Uncaught TypeError: Cannot set property 'className' of undefined

0
悬赏园豆:10 [待解决问题]

liItem[i].className = 'current';//第一种方式
liItem[i].setAttribute('class','current');//第二种方式
this.className = 'current';//第三种方式
为什么第三种方式可以使点击变色效果实现而第二、三两种方式都会报错呢?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<style type="text/css">
body {
position: relative;
width: 100vw;
height: 100vh;
background-repeat: no-repeat;
}
/* ul,li {
margin: 0px;
padding: 0px;
} */
.box {
width: 80vw;
height: 80vh;
}
ul {
width: auto;
height: auto;
margin: 0px;
padding: 0px;
border: none;
list-style-type: none;
background-color: rgba(50,150,150,0.3);
}
li {
display: inline-block;
padding: 4px;

		}
		.current {
			color: #FFFFFF;
			background-color: #2AC845;
		}
		.currentContent {
			display: '';
		}
		.none {
			display: none;
		}
	</style>

</head>
<body>
<div class="box">
<div class="nav-list">
<ul>
<li class="current">首页</li>
<li class="">下载</li>
<li>最新资讯</li>
<li>最新资讯</li>
</ul>
</div>
<div class="content">
<p class="">
这是具体内容1
</p>
<p class="none">
这是具体内容2
</p>
<p class="none">
这是具体内容3
</p>
<p class="none">
这是具体内容4
</p>
</div>
</div>
<script type="text/javascript">
var liItem = document.getElementsByTagName('li');
var con = document.querySelector('.content').querySelectorAll('p');
for(var i = 0;i < liItem.length;i ++) {
liItem[i].onclick = function () {
// liItem[i].className = 'current';//第一种方式
// liItem[i].setAttribute('class','current');//第二种方式
this.className = 'current';//第三种方式
}
}
</script>
</body>
</html>

小白兔有点裤的主页 小白兔有点裤 | 初学一级 | 园豆:155
提问于:2021-08-23 20:22

目前我能想到的就是,循环结束后也就是为4个li标签设置了点击事件函数之后,i的值变成了4,这个时候点击li标签,执行自定义函数,而这个时候liItem[i]里面的i值为4,然而从0-3一共4个li标签,下标4是表示第五个,显然没有定义第五个,这个时候就报错:TypeError: Cannot read property 'setAttribute' of undefined。无法读取未定义属性setAttribute.换成this的话,表示当前对象,也就是被点击的这个li标签。那么语义上就不会出现这个错误了

小白兔有点裤 2年前
< >
分享
所有回答(1)
0

把 var 换成 let 就可以用第一二种方式了

by.Genesis | 园豆:2719 (老鸟四级) | 2021-08-24 09:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册