【发布时间】:2015-03-05 02:05:22
【问题描述】:
我有一个命名空间,它有一种方法可以阻止在按键事件中输入某些字符以进行输入。如果检测到该字符,它会返回 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);
});
【问题讨论】:
-
尝试使用 keydown 事件
标签: javascript jquery namespaces