首页 > 解决方案 > 使用 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?

标签: javascripthtmlweb-frontend

解决方案


您可以检查课程并进行比较,然后根据它进行切换。下面是如何做到这一点的代码。刚刚删除了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>

推荐阅读