简体   繁体   中英

JavaScript .on(“keyup”)

There's an input text fires a function on "onkeyup" event. When that function fires I'm binding a "keyup" event with .on("keyup") method to get the last pressed key to find out if it was alphanumerical in order to fire the search ajax I want. And after I finish, I unbind the connection with .off("keyup") method.

But there's a problem with the unbindation. The problem is; My code runs once and doesn't run for a turn, then runs again and doesn't run for the other turn and keeps it going like that. I replaced the code I want to simplify it to test.

 $("#arama").on("keyup",function(event) { console.log("asd"); $("#arama").off("keyup"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="arama" /> 

Where am I mistaken ?

PS: I've solved it thanks to Chris.

Your code works for me (see below). Maybe check where you are binding your keyup event. It should be bound once when the document loads before the page shows. If you bind it multiple times (ie if the code that contains your keyup function runs more than once) you will run into problems.

 $("#arama").on("keyup", function(event) { var i = event.keyCode; if ((i >= 48 && i <= 57) || (i >= 96 && i <= 105)) { $("#arama").off("keyup"); console.log("Number pressed. Stopping..."); } else { console.log("Non-number pressed."); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="arama" /> 

No need to unbind the event. Try this

$("#arama").on("keyup",function(event) {
    console.log("asd");
});

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