首页 > 解决方案 > 如何在 javascript 函数中更改 span 内联元素的类?

问题描述

我正在尝试为具有眼睛图标(css class-fa fa-eye)的密码实现文本框。当用户单击眼睛图标时,它会变为斜线图标并将类型输入文本。

<div class="input-group show-hide-password">
      <form:password id="form-control" path="password" class="form-control" required="" />
       <div class="input-group-append">
         <span id="PassSpan" class="input-group-text" onclick="typeChange('form- 
         control','PassSpan')">
          <i class="fa fa-eye"  aria-hidden="true"></i> 
         </span>
       </div>
</div>

js文件

function typeChange(controlId, spanId) { 
     var x =  document.getElementById(controlId);        
     if (x.type === "password")
     { x.type = "text";         
     } 
     else { 
         x.type = "password";           
         } 
 }

此功能仅更改输入类型,但我无法将类更改为 fa fa-eye-slash。fa-eye 和 fa-eye-slash 类存在于 css 文件中。但我不确定如何更改它在 span 元素内的类。

有人可以帮我吗。

标签: javascriptcssbootstrap-4

解决方案


谢谢你们。我通过编写下面的新 js 函数解决了它,我在点击时调用它

function typeChange(controlId, spanId) { 
     var x =  document.getElementById(controlId);
     if ( spanId.classList.contains('fa-eye') ){
         spanId.classList.toggle('fa-eye-slash');
     }
     if (x.type === "password")
     { x.type = "text";      
     }
     else { 
         x.type = "password"; 

 }
 }

JSP

<i class="fa fa-eye" id ="passi" aria-hidden="true" onclick="typeChange('form-control',this)"></i>

推荐阅读