jQuery setTimeout 不起作用



我正在尝试比较两个密码字段,如果它们不匹配,则显示弹出窗口。

.HTML

<div class="form-group col-lg-6">
    <label>Password</label>
    <input type="password" class="form-control" name="password" id="password" required data-toggle="popover" title="Password Strength" value="" placeholder="Enter your password...">
</div>
<div class="form-group col-lg-6">
    <label>Repeat Password</label>
    <input type="password" class="form-control" name="passwordrep" id="passwordrep" value="" data-bind="popover" data-content="No match" placeholder="Confirm password...">
</div>

如果我不使用 setTimeout,我的 jQuery 代码就可以工作。但是我想在显示"不匹配"弹出框之前等待几秒钟。

.JS

function showPopover(id){
  $(id).popover('show');
}
var x_timer;
$("body").delegate('#passwordrep', 'keyup', function(){
    clearTimeout(x_timer);
    if($(this).val() != $('#password').val()){
      x_timer = setTimeout(function(){showPopover(this);}, 1000);
    }
    else {
      $(this).popover('hide');
    }
});

this不引用在setTimeout参数中调用事件处理程序的元素。您可以将参数传递给函数可用的setTimeout

setTimeout(function(elem){
   showPopover(elem);
}, 1000, this);

注意:delegate()已被弃用。自 jQuery 1.7 以来,它被 .on() 方法取代,


您也可以使用.bind()

setTimeout((function(){
   showPopover(this);
}).bind(this), 1000);
function checkPassword(elt1,elt2){
    return elt1.value()==elt2.value();
}

您可以在 Keyup 上调用它,您可以添加 if 以显示一些消息

最新更新