开发者

Why is the keydown event triggering more than one time

开发者 https://www.devze.com 2023-01-13 21:21 出处:网络
I am trying to create a suggestion list under a text input field.Currently I have the following code for the html of this list.

I am trying to create a suggestion list under a text input field. Currently I have the following code for the html of this list.

<div id="assigned_user_wrap">
   <input type="text" name="item" id="item" value="" />
</div>
<div id="suggestions">
   <ul>
      <li id="1">Item 1</li>
      <li id="2">Item 2</li>
      <li id="3">Item 3</li>
      <li id="4">Item 4</li>
      <li id="5">Item 5</li>
      <li id="6">Item 6</li>
   </ul>
</div>

The Javascript currently is the following:

$j('#item').focus(function() {

 // Register keypress events
 $j('#item').keydown(function(e) {
   console.log(e.keyCode);
   switch(e.keyCode) { 
     // User pressed "up" arrow
     case 38:
       e.preventDefault();
       navigate('up');
       console.log('up');
       break;
     // User pressed "down" arrow
     case 40:
       e.preventDefault();
       navigate('down');
       console.log('down');
       break;
     // User pressed "enter"
     case 13:
       e.preventDefault();
       if(item_name != '') {      
         $('#item').val(item_name);        
         console.log('item_name = ' + item_name);
        }
     break;
   }
 });

function navigate(direction){
  if($(":visible","#suggestions").length > 0){
  var lis = $j("li", "#suggestions");
  if(direction == "down"){
    var start = lis.eq(0);
  } else {
    var start = lis.filter(":last");
  }     
  var active = $j("li.active:first", "#suggestions");
  if(active.length > 0){
      if(direction == "down"){
          start = active.next();
      } else {
          start = active.prev();
      } 
  }
  lis.removeClass("active");
  start.addClass("active");

  item_name = start.text();

  }
}   

});//focus

Whe开发者_StackOverflow社区n I load the page and put my mouse on the text input field and start clicking the down arrow the highlighting of each of the items shows as expected. But as soon as I click off the input field and click any key then go back to the input field a second time and try to navigate through the list it will skip items. As you can see I have several console.log to show me what is happening. The logs indicate that when I click on the down or up arrow (one time) it triggers the event (keyDown) as happening multiple times which then makes it appear that it is skipping items. I can not figure out why it is doing this. Is there a way I can clear events after the text field becomes "focus" but before the keyDown occurs? Or am I writing something incorrectly?


because each time the element is being focused, an event keydown is added to it.

try putting $j('#item').keydown(function(e) { ... }); and also your function navigate outside focus event.

0

精彩评论

暂无评论...
验证码 换一张
取 消