$(function (){
$("#fullName").keydown(handleName);
});
function handleName(e){
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
}
在此过程中,我在keydown
上传递了handlename
,但它不起作用
Event.KeyCode已被弃用。 您应该改用e.which
。
Event.Which属性规范化Event.KeyCode和Event.CharCode。 建议观看Event.which用于键盘按键输入。 有关更多详细信息,请阅读MDN上的event.charcode。
https://api.jquery.com/event.which/
KeyboardEvent.KeyCode:不再建议使用此功能。 虽然某些浏览器可能仍然支持它,但它可能已经从相关的web标准中删除,可能正在被删除,或者可能只是出于兼容性的目的而保留。 避免使用它,如果可能的话更新现有代码; 请参阅本页底部的兼容性表,以指导您的决策。 请注意,此功能可能在任何时候停止工作。
https://developer.mozilla.org/en-us/docs/web/api/keyboardevent/keycode
和:https://developer.mozilla.org/en-us/docs/web/api/keyboardevent/keycode
有关您的代码的一些注意事项:
在设置侦听器时,最好定义一个匿名函数。 这将允许您向函数发送任何您想要的变量作为参数。
$(function (){
var testString = "this is an example of another variable";
$("#fullName").keydown(function(e) {
handleName(e, testString); //you can send in more than just the default event argument this way
});
});
另外,如果您的元素是动态创建的,那么您必须在这些元素上再次设置侦听器。 最好是针对您想要侦听的元素的某些父/祖先:
$(function (){
var testString = "this is an example of another variable";
//use .on() to set a listener on an ancestor node:
$(document).on("keydown", "#fullName", (function(e) {
handleName(e, testString); //you can send in more than just the default event argument this way
});
});
并且,正如我在评论中所说的,在代码的不同位置使用console.log
查看调用了什么以及使用了什么参数。 将此行作为HandleName()
函数的第一行:
console.log(“handleName()”,e,e.which);