jquery在keydown / up中选择li值

时间:2011-02-04 18:18:41

标签: jquery input html-lists

<input type="text" id="region" class="inputs" name="remo">

<ul id="ulList">
<li id="idr0"></li>
<li id="idr1">Baltimore</li>
<li id="idr2">India</li>
<li id="idr3">International - Russia</li>
<li id="idr4">MD 19940</li>
<li id="idr5">Minnesota</li>
<li id="idr6">North Carolina</li>
</ul>   

我需要jquery代码来选择keydown / up然后用li值设置输入值

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#region').live('keypress', function (e) {
                var objCurrentLi, obj = $('#ulList').find('.SelectedLi'), objUl = $('#ulList'), code = (e.keyCode ? e.keyCode : e.which);

                if (code === 40) {  //Up Arrow
                    if ((obj.length === 0) || (objUl.find('li:last').hasClass('SelectedLi') === true)) {
                        objCurrentLi = objUl.find('li:first').addClass('SelectedLi');
                    }
                    else {
                        objCurrentLi = obj.next().addClass('SelectedLi');
                    }
                    obj.removeClass('SelectedLi');
                }
                else if (code === 38) {  //Down Arrow
                    if ((obj.length === 0) || (objUl.find('li:first').hasClass('SelectedLi') === true)) {
                        objCurrentLi = objUl.find('li:last').addClass('SelectedLi');
                    }
                    else {
                        objCurrentLi = obj.prev().addClass('SelectedLi');
                    }
                    obj.removeClass('SelectedLi');
                }

                $(this).val(objCurrentLi.text());
            });
        });
    </script>
</head>
<body>
    <input type="text" id="region" class="inputs" name="remo" />
    <ul id="ulList">
        <li id="idr0"></li>
        <li id="idr1">Baltimore</li>
        <li id="idr2">India</li>
        <li id="idr3">International - Russia</li>
        <li id="idr4">MD 19940</li>
        <li id="idr5">Minnesota</li>
        <li id="idr6">North Carolina</li>
    </ul>
</body>
</html>