简体   繁体   中英

How to call a function on 'keydown' when an event is passed as a parameter in that function in jquery

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

In this I have passed handleName on keydown but it's not working

event.keyCode has been deprecated. You should use e.which instead.

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input. For more detail, read about event.charCode on the MDN.

https://api.jquery.com/event.which/

KeyboardEvent.keyCode: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

And: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode


Some notes about your code:

It's best to define an anonymous function any time you're setting a listener. This will allow you to send in any variables you'd like as arguments to the function.

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

Also, if your elements are created dynamically, you'd have to set the listener again on those. It's best to target some parent/ancestor of the element you want to listen to instead:

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

And, as I stated in my comment, use console.log in different places in the code to see what's being called, and with what arguments. Put this line as the first line in the function handleName() :

console.log("handleName()", e, e.which);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM