我正在尝试比较两个密码字段,如果它们不匹配,则显示一个弹出窗口。
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()
已被弃用。它已被 .on()
取代自 jQuery 1.7 以来的方法,
您还可以使用.bind()
setTimeout((function(){
showPopover(this);
}).bind(this), 1000);
关于javascript - jQuery setTimeout 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44545439/