JQuery - 附加Enter KeyPress事件以列出项目

时间:2011-06-20 21:07:51

标签: jquery plugins autocomplete

我正在使用jquery编写自己的自动完成插件。列表项是基于json响应动态绘制的。我有上/下箭头键代码,适用于在输入字段上触发的键盘事件。

我想在每个列表项中添加一个回车键事件。因此,当用户使用向上/向下箭头键浏览自动完成下拉列表时,输入键按下事件会将该列表项的值添加到输入字段。

有人可以帮忙吗?我已经尝试将事件绑定到列表项

if (e.keyCode == 40){ 
    // highlight the list item
    $("li").bind("keyup",function(e){
        if (e.keyCode == 13){
            // add value of list item to input field
        }
    });
}

4 个答案:

答案 0 :(得分:2)

你不能只使用bind,因为在评估javascript时列表项不在DOM中。

使用jQuery.live()http://api.jquery.com/live/

如果您有<div id='autocomplete'><li>...</li></div>,那么您可以调用直播活动,如:

$("#autocomplete li").live("keyup", function(e) {
    if (e.keyCode == 40)
        // Add to the input field
});

答案 1 :(得分:1)

这样的事情:

$("input").live("keypress", function(keyarg){
 if(keyarg.keyCode == 13) { //Enter keycode
   $("WHATEVERELEMENT").append($(this).val());
 }
});

为了扩展你的评论,这里有一个jfiddle http://jsfiddle.net/csLVX/5/:{稍微整理我的代码!}

    <ul>
        <li>ITEM 1</li>
        <li>ITEM 2</li>
        <li>ITEM 3</li>
    </ul>
    <br /><input/>



   liPossition = 0;

$("input").live("keyup",function(e){ 
     if (e.keyCode == 40) { // down arrow key code 
        if (liPossition != $("li").length-1) {
          liPossition++;
        }
        $("input").val($("li:eq("+liPossition+")").text());


    } if (e.keyCode == 38) { // up arrow key code        
       if (liPossition == -1) {
            //if we reach min items do nothing
           liPossition = 0;
        } else {
            liPossition--;
        }
        $("input").val($("li:eq("+liPossition+")").text());

    } if (e.keyCode == 13) { // enter key code 
    //some code to proceed the form
    } 
}); 

答案 2 :(得分:0)

您可能希望使用live()而不是bind(),这样即使动态加载li,它也能正常运行。

The docs are here

我还会在li中添加一个特定的类,以便您可以使用以下选择器:

$('.my_loaded_selection').live('keyup', function(e){//do your thing
}) ;

答案 3 :(得分:0)

countries = ['name1', 'name2']);

//Номер активного элемента в списке подсказок
numActiveItem = 0;


//Количество элементов в списке подсказок
countItemsListHelp = 0;

// Создание списка подсказок
function createHelpList(event) {
    var event = event || window.event;
    var key = event.keyCode || event.charCode;
    var target = event.target || event.srcElement;
    var len_key_words = target.value.length;
    var reg = new RegExp("^" + target.value + ".*$", "i");
    counter = 0;

    // Нажат Enter
    if (key == 13) {
        document.getElementById("select_list").style.display = 'none';
    }
    /* Перебор подсказок */
    else if (key == 40 || key == 38 && countItemsListHelp != 0) {
        alert(countItemsListHelp);
        if (key == 40) numActiveItem++;
        else numActiveItem--;

        if (numActiveItem > countItemsListHelp) numActiveItem = 1;
        else if (numActiveItem < 1) numActiveItem = countItemsListHelp;


        for (i = 0; i < document.getElementById('select_list').childNodes.length; i++) {
            if (document.getElementById('select_list').childNodes[i].nodeType == 1) {
                counter++;
                document.getElementById('select_list').childNodes[i].style.background = '#ffffff';
                if (counter == numActiveItem) {
                    document.getElementById('select_list').childNodes[i].style.background = '#fdedaf';
                    document.getElementById('search_field').value = document.getElementById('select_list').childNodes[i].getElementsByTagName('span')[0].innerHTML;
                }
            }
        }
    }
    /* Поиск и вывод подсказок */
    else if (len_key_words && key != 37 && key != 39) {
        numActiveItem = 0;
        document.getElementById('select_list').style.display = 'none';
        code = '';
        for (i = 0; i < countries.length; i++)
            if (reg.exec(countries[i].substr(0, len_key_words)) != null) {
                code += "<li><span style='display: none;'>" + countries[i] + "</span><strong>" + countries[i].substr(0, len_key_words) + "</strong><span style='color: #b4b3b3'>" + countries[i].substr(len_key_words) + "</span></li>";
                counter++;
            }
        if (counter) {
            countItemsListHelp = counter;
            document.getElementById('select_list').innerHTML = code;
            document.getElementById('select_list').style.display = 'block';
        }
    }
    /* Если поле пустое*/
    else if (!len_key_words) {
        document.getElementById('select_list').style.display = 'none';
    }
}

function selectHelp(ev) {
    var event = ev || window.event;
    var target = event.target || event.srcElement;
    document.getElementById('search_field').value = target.getElementsByTagName('span')[0].innerHTML;
    document.getElementById('select_list').style.display = 'none';
}