我有一个代码,可以根据我的真实值来创建和输出不同的变量。变量。真实="名称"工作完美,但当我更新真相到#34;电子邮件"变量突然重复多次击键。任何帮助将不胜感激。
var cmd = "";
var cmd1 = "";
var truth = "name";
$(document).ready(function() {
$("#contactlink a").click(function(){
$(document).keyup(function(event){
if (truth == "name"){
if (event.which == 8){ //backspace deletes last character of string
cmd = cmd.substring(0, cmd.length - 1);
}
else if (event.which == 13){
var name = cmd;
$("#emailcontact").typed({
strings:["<br/><br/>Email Address: "],
typeSpeed: 10,
showCursor: false
});
truth = "email";
}
else if ((event.which >= 65 && event.which <= 90) || event.which == 32){
if (cmd.length == 0){
cmd = cmd + String.fromCharCode(event.which);
}
else if (cmd.substring(cmd.length-1,cmd.length) == " "){
cmd = cmd + String.fromCharCode(event.which);
}
else{
cmd = cmd + String.fromCharCode(event.which).toLowerCase();
}
}
$('#namecontact').text(cmd);
}
else if (truth == "email"){
if (event.which == 8){ //backspace deletes last character of string
cmd1 = cmd1.substring(0, cmd1.length - 1);
}
else if (event.which == 13){
var name = cmd1;
$("#emailcontact").typed({
strings:["<br/><br/>Email Address: "],
typeSpeed: 10,
showCursor: false
});
var cmd2;
}
else if ((event.which >= 65 && event.which <= 90) || event.which == 32){
cmd1 = cmd1 + String.fromCharCode(event.which).toLowerCase();
}
$('#emailcontact').append(cmd1);
}
});
});
});
答案 0 :(得分:3)
这是因为每次点击$(document).keyup(...)
元素时,您都会添加新的#contactlink a
侦听器。
为了防止你做这样的事情:
$("#contactlink a").click(function(){
$(document).off("keyup");
$(document).on("keyup", function(event){
});
});
这样做是为了在再次添加之前删除先前添加的侦听器。