【问题标题】:Keyup event is hanging up my laptop ( My keyboard got stuck )Keyup 事件正在挂断我的笔记本电脑(我的键盘卡住了)
【发布时间】:2016-12-30 06:57:49
【问题描述】:
我正在使用 ajax 来检查我数据库中的电子邮件 ID。我正在使用 keyUp 事件来实时检查它。它工作正常,但我的键盘卡住了。请建议
$("#email").on("keyup",function(){
});
$("#email").on("keyup",function(){
// now check if email id is changed
var e= $("#email").val();
if(e!="<?=$user_info[0]['user_email']?>" && e!=""){
$.ajax({
url:"<?=URL?>users/check-user-email",
type:'get',
async:false,
data:{email:e},
success:function(resp){
console.log(resp);
if(resp=="Email exists"){
$("#emailerror").css({'display':'block'});
$("#submit").prop("disabled",true);
}else{
$("#emailerror").css({'display':'none'});
$("#submit").prop("disabled",false);
}
}
});
}
});
【问题讨论】:
标签:
jquery
performance
keyup
onkeyup
【解决方案1】:
您不应该使用async:false, 它对同步调用进行异步调用,这不是ajax 实现所必需的。
在您的情况下,因为您没有任何用于在特定时间过去后触发某些事件的去抖动方法。超时可用于创建去抖动。如:
var time;
$("#email").on("keyup", function() {
if (time) {
clearTimeout(time); // <----clears the timeout for every stroke but **last**.
}// so if you keyup for "abc" then call for 3rd stroke initialized for the word "abc".
time = setTimeout(function() {
// now check if email id is changed
var e = $("#email").val();
if (e != "<?=$user_info[0]['user_email']?>" && e != "") {
$.ajax({
url: "<?=URL?>users/check-user-email",
type: 'get',
//async: false, // <-------remove it or comment out.
data: {
email: e
},
success: function(resp) {
console.log(resp);
if (resp == "Email exists") {
$("#emailerror").css({
'display': 'block'
});
$("#submit").prop("disabled", true);
} else {
$("#emailerror").css({
'display': 'none'
});
$("#submit").prop("disabled", false);
}
}
});
}
}, 500); // <----you can register for more than 500 ms.
});
【解决方案2】:
对于每个 keyup,回调方法都会被调用,这是它的主要原因。
取而代之的是,您可以使用 debounce 它将在一定间隔后调用。使用下划线 js 查看此链接:
http://underscorejs.org/#debounce
var someFunction = function (){
// now check if email id is changed
var e= $("#email").val();
if(e!="<?=$user_info[0]['user_email']?>" && e!=""){
$.ajax({
url:"<?=URL?>users/check-user-email",
type:'get',
async:false,
data:{email:e},
success:function(resp){
console.log(resp);
if(resp=="Email exists"){
$("#emailerror").css({'display':'block'});
$("#submit").prop("disabled",true);
}else{
$("#emailerror").css({'display':'none'});
$("#submit").prop("disabled",false);
}
}
});
}
}
$("#email").on("keyup", _.debounce(someFunction, 1000, true));