Switch Bootstrap 输入变化时的图标

Switch Bootstrap Icons on change of input

我正在处理密码输入,这是用户的情况。

这是代码(只注意If结构),下面我会解释问题。

    $('#id_password.form-control').on('change', function(){
    var inputVal = $(this).val(); //Quand on appelle this, on récupère la valeur dans laquelle elle est utilisée.
    var passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/;
    if(!passwordReg.test(inputVal) || ($(this).val() == "")){
        $(this).after('<span style="color:red;" class="glyphicon glyphicon-remove"></span>');
        $(this).removeClass("glyphicon glyphicon-ok");
    }
    else{
        $(this).after('<span style="color:green" class="glyphicon glyphicon-ok"></span>')
        $(this).removeClass("glyphicon glyphicon-remove");
    }
});

我的代码有两个问题:

如果你有一些想法或者你想要更多的细节,我是开放的,我想纠正我的错误以便注意到它=)

感谢您抽出宝贵时间,祝您在代码中度过愉快的一天=)

问题是因为您要从之前添加的 span 中删除 class,而不是删除 span 本身。您可以使用 .next('span').remove() 来做到这一点,如下所示:

$('#id_password.form-control').on('change', function(){
    var $input = $(this);
    var inputVal = $input.val();
    var passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/;

    $input.next('span').remove();
    if ($input.val() == "" || !passwordReg.test(inputVal)) {
        $input.after('<span style="color: red;" class="glyphicon glyphicon-remove"></span>');
    }
    else {
        $input.after('<span style="color: green" class="glyphicon glyphicon-ok"></span>')
    }
});

Working example

尝试以下操作:

 $('#id_password.form-control').on('input', function(){

   $(this).parent().find('.glyphicon').remove();//remove the icons each time the input changes


    var inputVal = $(this).val(); //Quand on appelle this, on récupère la valeur dans laquelle elle est utilisée.
    var passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/;
    if(!passwordReg.test(inputVal) || ($(this).val() == "")){
        $(this).after('<span style="color:red;" class="glyphicon glyphicon-remove"></span>');
    }
    else{
        $(this).after('<span style="color:green" class="glyphicon glyphicon-ok"></span>');
    }
});

演示:https://jsfiddle.net/L3z2sdLr/

另一种方法是使用 form-group 等,看起来更漂亮一些 Bootstrap:

Fiddle https://jsfiddle.net/p1rchywb/5/

HTML

<div class="form-group has-feedback">
  <label class="control-label" for="password">Enter Your Password</label>
  <input type="text" class="form-control" id="password">
  <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
</div>

jQuery

$("#password").on("change", function() {
  var passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/;
  if($(this).val() !== "" || passwordReg.test($(this).val()) ) {
    $(this).next().removeClass("glyphicon-remove").addClass("glyphicon-ok");
  } else {
    $(this).next().addClass("glyphicon-remove").removeClass("glyphicon-ok"); 
  }
});