首页 > 解决方案 > 当事件作为参数在jquery中的该函数中传递时,如何在'keydown'上调用函数

问题描述

$(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();
        }
    }
 }

在这我已经过去了handleNamekeydown但它不起作用

标签: javascriptjqueryjquery-events

解决方案


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);


推荐阅读