Javascript 在hidde/show password函数中保存单击事件的状态

Javascript 在hidde/show password函数中保存单击事件的状态,javascript,Javascript,如何保存单击事件的状态,以及当显示密码时,眼睛按钮应隐藏密码 <div class="input-group"> <input type="password" value="test value" name="password" id="id_password" class="form-control" placeholder="Password"> <span id="show_password" title="Click here to show

如何保存单击事件的状态,以及当显示密码时,眼睛按钮应隐藏密码

<div class="input-group">
    <input type="password" value="test value" name="password" id="id_password" class="form-control" placeholder="Password">
    <span id="show_password" title="Click here to show/hide password" class="input-group-addon" style="cursor: pointer;"><i id="button-eye" class="fa fa-eye"></i></span>
</div>

示例:

更改您的if
为什么需要保存状态?使用输入状态

if (eye_button_checked) {


函数作用域变量在每次调用时都会被创建和销毁,并且无法维护其状态

您有多种方法可以解决此问题:

  • 使用全局变量(由于全局范围污染,不建议使用)

  • 或者,使用块作用域变量和封装该变量的块(防止在外部访问):

  • 或者,您可以检查
    密码
    元素的
    类型
    ,并将其反转:

    var eye_button = document.querySelector('#button-eye');
    eye_button.addEventListener('click', function (event) {
        var password = document.querySelector('#id_password');
        console.log("click");
    
    
        password.type = password.type === 'password' ? 'text' : 'password';
        // need to change icon to fa-eye-slash and change password.type to password again
    
    }, false);
    

根据您的代码,每次单击都会将选中的
眼睛按钮重置为
true
。您需要将声明和初始化移到click handler函数之外。这里有一个固定版本:@ChrisG请将此添加为应答这基本上是的副本,其余只是实现细节或将您的眼睛放在按钮上\u checked=true;失灵
if (password.type == "text") {
var eye_button = document.querySelector('#button-eye');
var eye_button_checked = false
eye_button.addEventListener('click', function (event) {
    var password = document.querySelector('#id_password');
    console.log("click");

    //Invert the variable
    eye_button_checked=!eye_button_checked

    password.type = eye_button_checked ? 'text' : 'password';
    // need to change icon to fa-eye-slash and change password.type to password again

}, false);
var eye_button = document.querySelector('#button-eye');
{
    let eye_button_checked = false
    eye_button.addEventListener('click', function (event) {
        var password = document.querySelector('#id_password');
        console.log("click");

        //Invert the variable
        eye_button_checked=!eye_button_checked

        password.type = eye_button_checked ? 'text' : 'password';
        // need to change icon to fa-eye-slash and change password.type to password again

    }, false);
}
//eye_button_checked can't be accessed here
var eye_button = document.querySelector('#button-eye');
eye_button.addEventListener('click', function (event) {
    var password = document.querySelector('#id_password');
    console.log("click");


    password.type = password.type === 'password' ? 'text' : 'password';
    // need to change icon to fa-eye-slash and change password.type to password again

}, false);