1

我有一个<input id="#locKeySearch">和一个<div id="#locDropDown">。当我输入我的input字段时,我通过 AJAX 在div.

现在我想通过箭头键获得更多功能↓</kbd>/↑</kbd>. I want to select my <a> tags and when they are selected their backgrounds change and on pressing Enter, the browser navigates to the appropriate location.

有人可以帮我吗?

CSS:

div {width:300px;}
a{display:block;}
a:hover{background:#ccc;}

JavaScript:

$(document).ready(function() {
  $('#locKeySearch').keydown(function(e)
    {<br>
      var alinks = $('#locDropDown').find('a');
      if(alinks.length > 0)
      {
        alinks.each(function(){

          if (e.keyCode === 40)//Down Arrow
          {
              e.preventDefault();
              var current = alinks.index(),
              next = $(this).next();
              this.blur();
              setTimeout(function() { next.focus().select(); }, 50);
          }
        });
      }
    });
  });

HTML:

<form>
    <input type="text" name="locKeySearch" id="locKeySearch" value="" />
</form>
<div id="locDropDown">
    <a href="1">1</a>
    <a href="2">2</a>
    <a href="3">3</a>
    <a href="4">4</a>
    <a href="5">5</a>
    <a href="6">6</a>
    <a href="7">7</a>
    <a href="8">8</a>
    <a href="9">9</a>
    <a href="10">10</a>
</div>
4

1 回答 1

1

我已经解决了上面的查询。下面是答案

function keyEvents()
{
    var keyindex,alinks;
    keyindex = -1;
    // Key Events
    $('#locKeySearch').keydown(function(e){
        alinks = $('#locDropDown').find('a');
        if(alinks.length == 0)
        {
            keyindex = -1;
        }
        if(e.keyCode == 40)
        {
            e.preventDefault();
            if(alinks.length > 0 && keyindex == -1)
            {
                keyindex = 0;
                $('#locDropDown').find('a')[keyindex++].focus();
            }
        }
    });

    $('#locDropDown').keydown(function(e)
    {
        alinks = $('#locDropDown').find('a');
        if(e.keyCode == 40)
        {
            e.preventDefault();     
            if(keyindex == -1)
            {
                keyindex = 1;
            }
            if(alinks.length > 0 && keyindex < alinks.length)
            {
                $('#locDropDown').find('a')[keyindex++].focus();
            }
        }
        if(e.keyCode == 38)
        {
            e.preventDefault();
            if(keyindex == alinks.length)
            {
                keyindex = keyindex-2;
            }

            if(alinks.length > 0 && keyindex < alinks.length && keyindex >=0)
            {
                $('#locDropDown').find('a')[keyindex--].focus();
            }
        }
    });

}
于 2012-09-13T16:03:49.730 回答