带有搜索框的jQuery关键事件 [英] jQuery Key Events with a Search Box

查看:62
本文介绍了带有搜索框的jQuery关键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的autosuggest插件,我想添加Keypress事件,以便用户可以向下和向上箭头。此外,如果他们按Enter键,它会将值添加到输入。

I'm working on an autosuggest plugin with jQuery, and I'd like to add Keypress events so that users can arrow down and up. Also, if they press enter it will add the value to the input.

这就是我的HTML的样子:

This is what my HTML looks like:

 <input id="myInput" class="textInput" type="text" name="instructorName"/>
     <label for="search">  </label>
        <div id="myInputResults" class="results" style="display: block;">
           <ul>
            <li><a><div class="suggClass">Suggestion #1</div></a></li>
            <li><a><div class="suggClass">Suggestion #2</div></a></li>
            <li><a><div class="suggClass">Suggestion #3</div></a></li>
            <li><a><div class="suggClass">Suggestion #4</div></a></li>
          </ul>
         </div>

到目前为止,我有这样的事情:

So far, I have something like this:

  $("#myInput").keyup(function (e) { 

     var code = (e.keyCode ? e.keyCode : e.which);

     if (code == 40) {             //If user "keys down"

              //I would want to addClass 'hovered' to the "first <li>"
             // Remove 'hovered' class from any other <li>'s

         }


    });

到目前为止,我不太确定使用的正确逻辑,以便用户可以向上,向下滚动,然后按输入选择项目。

Up to this point, I'm not quite sure on the proper logic to use so that users can scroll up, down, and press 'enter' to select an item.

任何建议和帮助都将非常感谢!谢谢。

Any suggestions and help on this would be greatly appreciated! Thank you.

推荐答案

添加到Psytronic的代码上,这应该包括输入键码......

Adding onto Psytronic's code, this should cover the "enter" keycode as well...

$(function(){
  $("#myInput").keyup(function (e) { 
        var code = (e.keyCode ? e.keyCode : e.which);

        if (code == 40) {
            if($("li.hovered").length == 0){
                $("#myInputResults li").eq(0).addClass("hovered");
            }else{
                $("li.hovered").eq(0).removeClass("hovered").next().addClass("hovered");
            }
        };

        if(code == 13) {
            if($("li.hovered").length > 0){
                $("#myInput").val($("li.hovered").eq(0).find("div.suggClass").eq(0).text());
            }
        }
    });
});

这篇关于带有搜索框的jQuery关键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆