2017-06-14 82 views
0

我想比较两个密码字段,并显示一个Popover,如果他们不匹配。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'); 
    } 
}); 
+0

我认为你的代码不起作用,因为'this'不是你认为它在关闭。要小心,用'this'在闭包外部正确设置变量,然后使用变量。 – sjahan

+0

或使用es6箭头功能 –

+0

这是什么样的标题?它没有描述真正的问题,并且'jquery'也没有任何与'setTimeout'有关的事情 – vsync

回答

2

this不指调用的事件处理程序在setTimeout参数元素。您可以传递参数给setTimeout这将是提供给函数

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

注:delegate()已被弃用。它是由.on()方法,因为jQuery的1.7取代,


您还可以使用.bind()

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

可以称之为上KEYUP,您可以添加如果显示一些消息

0

谢谢!它与.bind() 我爱你们