简体   繁体   English

JavaScript .on(“keyup”)

[英]JavaScript .on(“keyup”)

There's an input text fires a function on "onkeyup" event. 有一个输入文本在“onkeyup”事件上触发一个函数。 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. 当该函数触发时,我正在使用.on(“keyup”)方法绑定“keyup”事件,以获取最后一个按下的键,以查明它是否为字母数字,以便触发我想要的搜索ajax。 And after I finish, I unbind the connection with .off("keyup") method. 在我完成之后,我解除了与.off(“keyup”)方法的连接。

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. PS:感谢克里斯,我已经解决了。

Your code works for me (see below). 您的代码适合我(见下文)。 Maybe check where you are binding your keyup event. 也许检查你绑定你的keyup事件的位置。 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. 如果多次绑定它(即如果包含您的keyup函数的代码运行多次),您将遇到问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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