开发者

jquery handle keypress for list

开发者 https://www.devze.com 2023-01-28 02:54 出处:网络
I have a list like: <div id=\"txt\"></div> <ul><li><a href=\"#\">Tom</a></li><li><a href=\"#\">Tina</a></li><li><a href=\"#\

I have a list like:

<div id="txt"></div>
<ul><li><a href="#">Tom</a></li><li><a href="#">Tina</a></li><li><a href="#">Berba</a></li><li><a href="#">Tyson</a>开发者_开发技巧</li><li><a href="#">Bank</a></li></ul>

my goal is: when i press a key like "T" and "Tom" will appear in #txt, and press "T" once more time, Tina will replace Tom in #txt.

I can't find a solution for this!!! :(

Someone can help me? Thanks


Listen keydown event, get keycode, get target name set , loop name.
It may like this

var lastchar, i=-1;
$(document).bind('keydown',function(e){
  var char = String.fromCharCode(e.which),
      names = $('li a').filter(function(){
        return $(this).text().charAt(0)==char;
      });
  if( !names.length ){ return; }

  if( char != lastchar ){ i=-1; }
  $('#txt').text( names.eq( ++i % names.length ) );
});
0

精彩评论

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