我有这段代码:
container.unbind('keypress').bind('keypress',function (e) {
var code = e.which,
charac = String.fromCharCode(code),
totalChar = $(this).text().replace(/\s+/g, ''),
diff,
previousChar = publisher.typeHistory.length > 0 ? publisher.typeHistory[publisher.typeHistory.length-1]:''
previousCharCode = previousChar.charCodeAt(0);
if(e.keyCode === undefined){ // backspace
getCharacterDiff();
console.log(totalChar.length-1);
if(totalChar.length-1 === 0){
publisher.typeHistory = [];
}
}
console.log(previousChar);
if(isCharacterKeyPress(code)){
if (charac.toUpperCase() != charac.toLowerCase() ) { // Is a char or space
if(charac === charac.toUpperCase()){ // Is a char upper ?
if(previousChar === ' '){
console.log('upper + previous == space ', publisher.typeHistory);
}else {
publisher.typeHistory = [];
}
push = true;
}
else if (charac === charac.toLowerCase()){
if(previousCharCode === 32){
publisher.typeHistory = [];
}
if(hasUpperCase(publisher.typeHistory.join(''))){
push = true;
}
else {
push = false;
}
}
else {
push = false;
}
}
else if (code === 32){
console.log('space');
console.log(previousCharCode);
if (previousCharCode === 32){
push = false;
publisher.typeHistory = [];
}
// else if(previousChar === 32) { // is the spacebar ?
// console.log(previousChar);
// }
}
else { // = it's a number / , / ., etc..
console.log('not chara or space');
push = false;
publisher.typeHistory = [];
}
if (push) {
publisher.typeHistory.push(charac);
}
}
console.log(publisher.typeHistory);
previousTotal = publisher.typeHistory.join('');
if (publisher.typeHistory.length > 2) {
exp = publisher.typeHistory.join('');
publisher.getResults(service,type,exp);
}
else {
if(publisher.typeHistory.length === 0){
publisher.typeHistory = [];
}
publisher.hideResults();
}
});
这样,我可以处理在具有的元素中键入的键contenteditable=true
,然后将其发送到向PHP脚本发出请求的方法。
在这里,container
可以是具有contenteditable = true的任何元素。
问题是:我用于e.keyCode === undefined
检查用户是否键入退格键,以便可以更新请求。但是e.keyCode === undefined
仅适用于单个元素,不适用于其他元素(另一方面,不会触发keypress事件)。
所以我不知道这是从哪里来的:
container
我想念什么?
从MDN上的按键事件:
当按下某个键时会触发keypress事件,并且该键通常会产生一个字符值
因此,您必须对某些键使用keyup
或keydown
事件,例如转义键或退格键,因为它们不会产生字符。
退格键的键码是8
,因此您的代码可能如下所示:
container.unbind('keyup').bind('keyup',function (e) {
...
if(e.keyCode === 8){ // backspace
getCharacterDiff();
console.log(totalChar.length-1);
if(totalChar.length-1 === 0){
publisher.typeHistory = [];
}
}
...
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句