javascript - 在更新元素的类名时,为什么需要“this”关键字?
问题描述
我指的是例子
// Get the container element
var btnContainer = document.getElementById("myDIV");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
.btn {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
/* Style the active class (and buttons on mouse-over) */
.active, .btn:hover {
background-color: #666;
color: white;
}
<div id="myDIV">
<button class="btn">1</button>
<button class="btn active">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
</div>
在此将活动类替换为 nil,current[0].className
如下所示
current[0].className = current[0].className.replace(" active", "");
但是要添加类名,this
使用关键字
this.className += " active";
为什么我不能添加新的类名如下
current[0].className += " active";
?
解决方案
因为this
在您当前的上下文中是单击的按钮。另一种方法是使用e.target.classList.add('active');
,但在这样做之前,您应该e
像这样传递给回调函数参数
btns[i].addEventListener("click", function(e) {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
e.target.classList.add('active');
});
推荐阅读
- identityserver4 - Identity Server 4 IDP Auto-redirect to external provider
- selenium - 如何在硒中找到具有多个类的元素
- php - laravel 5.6 Eloquent One to Many Relationship on multiple tables
- scala - 这个 flatMap 代码背后的魔力是什么?
- excel - Userform TextBox not Reading Large Numbers
- powerbi - Split custom fields in Power BI
- python - Jupityr notebook kernel error - FileNotFoundError: [WinError 2]
- android - Kotlin - 使用 Persistence Room:runtime lib 从 Room 数据库返回新插入的 id
- java - 我们可以用 play java 框架实现 testNG 吗?
- monitoring - 在zabbix中使用活动代理监控日志文件?