鼠标点击只会让一个产生效果
有dalao能说说最后的this指代的是什么元素么
为什么把this改成btns 或者 btns[i] 都会报错
Uncaught TypeError: Cannot set property ‘backgroundColor’ of undefined
at HTMLButtonElement.btns..onclick (html:40)
<!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>
body {
display: flex;
justify-content: center;
}
button {
width: 80px;
height: 35px;
background-color: transparent;
outline: none;
margin-left: 10px;
}
</style>
</head>
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<script>
var btns = document.getElementsByTagName('button');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function(){
for(var i = 0 ; i < btns.length ; i++){
btns[i].style.backgroundColor = '';
}
this.style.backgroundColor = 'darkred'
}
}
</script>
</body>
</html>
这篇博客探讨了如何使用JavaScript实现一种排他效果,即点击按钮时只有被点击的按钮生效。作者遇到了在处理`this`关键字时的问题,当尝试将`this`替换为`btns`或`btns[i]`时,出现了`Cannot set property 'backgroundColor' of undefined`的错误。文章邀请读者解答`this`在该场景下所指代的元素。
1687

被折叠的 条评论
为什么被折叠?



