我有一个命名空间,其中包含一个方法来阻止在按键事件中输入某些字符以进行输入。如果检测到该字符,则返回false,但我认为因为在触发按键时调用了该字符,所以仍会输入该字符。我该如何解决这个问题?
如果我从命名空间中取出该功能,它按预期工作,但我不想要它。
HTML
<div id="personal-info">
<input id="first-name" class="personal-info" autofocus/><p id="error-first-name" class="error-text"></p>
<input id="last-name" class="personal-info"/><p id="error-last-name" class="error-text"></p>
</div>
使用Javascript:
fsa = (function() {
//OK - get selected element ID and write ID
var inputId = "";
var sigId = "";
var errId = "";
function GetAndSetLoc() {
inputId = document.activeElement.id;
sigId = "sig-" + document.activeElement.id;
errId = "error-" + document.activeElement.id;
}
var thisId = "";
// on button down, if the character is illegal, change the css of the error box
function showError(keyCode) {
var keys = [13,
"<".charCodeAt(0),
">".charCodeAt(0),
"$".charCodeAt(0),
"(".charCodeAt(0),
")".charCodeAt(0),
"?".charCodeAt(0),
"{".charCodeAt(0),
"}".charCodeAt(0),
"/".charCodeAt(0),
"#".charCodeAt(0),
"&".charCodeAt(0),
"*".charCodeAt(0),
"@".charCodeAt(0),
"~".charCodeAt(0)
];
var index;
for (index = 0; index < keys.length; ++index) {
if (keys[index] === keyCode) {
errorObject = $('#' + errId);
errorObject.html("Sorry, invalid character.").addClass('error');
setTimeout(function() {
errorObject.html("Sorry, invalid character.").removeClass('error');
}, 2000);
return false;
}
}
}
return {
GetAndSetLoc: GetAndSetLoc,
showError: showError
}
})();
// --------- Call the functions
//OK - get current read and write ids
$('.personal-info').focus(function(){
fsa.GetAndSetLoc();
});
$("input").keypress(function(e) {
fsa.showError(e.keyCode);
});
答案 0 :(得分:0)
从keypress事件返回 false
$("input").keypress(function(e) {
return fsa.showError(e.keyCode);
});