使用addEventListener点击将图标开关从打开的fas fa切换到打开的fas fa


const newLock = document.createElement("i"); 
newLock.setAttribute("class", "fas fa-lock-open") 
newLock.setAttribute("id", color + "lock"); 

如何使用addEventListener点击将图标从fas fa锁定打开切换到fas fa锁定?

您可以检查类并对其进行比较,并在此基础上切换它。下面是如何执行的代码。刚刚删除了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>

最新更新