javascript - 使用 addEventListener click 切换图标从 fas fa-lock-open 切换到 fas fa-lock
问题描述
const newLock = document.createElement("i");
newLock.setAttribute("class", "fas fa-lock-open")
newLock.setAttribute("id", color + "lock");
如何使用 addEventListener click 将图标切换从 fas fa-lock-open 切换到 fas fa-lock?
解决方案
您可以检查课程并进行比较,然后根据它进行切换。下面是如何做到这一点的代码。刚刚删除了i而不是按钮。
<html>
<body class="body">
Hello
</body>
</html>
<script>
function load(){
const newLock = document.createElement("button"); // put I here I just added so that I can use click event
newLock.setAttribute("class", "fas fa-lock-open")
newLock.setAttribute("id", "lock");
newLock.innerHTML = 'H';
document.body.append(newLock);
newLock.addEventListener('click',function(e){
let i = document.getElementById(e.srcElement.id);
if(i.getAttribute('class') === 'fas fa-lock-open'){
i.removeAttribute("class", "fas fa-lock-open");
i.setAttribute("class", "fas fa-lock");
}else{
i.removeAttribute("class", "fas fa-lock");
i.setAttribute("class", "fas fa-lock-open");
}
});
}
load();
</script>
推荐阅读
- php - 我有问题从mysql按年分组数据值
- vim - Vim 获取/设置缓冲区名称而不输入缓冲区
- notepad++ - Notepad++ - 将来自 SQL Server 的大查询变成一行
- sql-server - Oracle Varchar2 到 SQL Server Varchar
- php - PHP 错误页面(自定义)
- docker - ddev start 报错:当前安装的 docker 版本不符合 ddev 的要求:17.6.2-ce is less than 18.06.0-ce
- robots.txt - Googlebot 无法获取此页面的所有资源
- azure - Application Insight 日志 403
- responsive-design - Bootstrap 4.1 carousel-fade 响应式图像效果
- meteor - 获得流星谷歌日历的权限不足