最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript .on("keyup") - Stack Overflow

programmeradmin0浏览0评论

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=".1.1/jquery.min.js"></script>
<input id="arama" />

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="arama" />

Where am I mistaken ?

P.S: I've solved it thanks to Chris.

Share Improve this question edited Apr 15, 2017 at 15:53 Ümit Aparı asked Apr 15, 2017 at 15:02 Ümit AparıÜmit Aparı 5682 gold badges7 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

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 (i.e. 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./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");
});
发布评论

评论列表(0)

  1. 暂无评论