【问题标题】:JQuery - Attaching Enter KeyPress event to list itemsJQuery - 附加 Enter KeyPress 事件以列出项目
【发布时间】:2011-06-20 21:07:51
【问题描述】:

我正在用 jquery 编写我自己的自动完成插件。列表项是根据 json 响应动态绘制的。我有向上/向下箭头键代码,可以很好地处理在输入字段上触发的 keyup 事件。

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

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

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
        }
    });
}

【问题讨论】:

  • 我也一直在为 jQuery 编写一个自动完成插件。如果你的项目还不算太远,check it out.

标签: jquery plugins autocomplete


【解决方案1】:

您不能只使用绑定,因为在评估该 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
});

【讨论】:

  • @john 抱歉,我没有复制你的答案。
  • 这就是我所做的: $("input."+id).live("keyup",function(e){ if (e.keyCode == 40) { // 向下箭头键code } if (e.keyCode == 38) { // 向上箭头键代码 } });
【解决方案2】:

类似这样的:

$("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
    } 
}); 

【讨论】:

  • 谢谢! live() 工作但有一个问题。这就是我正在做的: $("input."+id).live("keyup",function(e){ if (e.keyCode == 40) { // 向下箭头键代码 } if (e. keyCode == 38) { // 向上箭头键代码 } if (e.keyCode == 13) { // 输入键代码 } }); Enter Key 有效,但它始终返回第一个列表项的值。我想获取由向上/向下箭头键突出显示的列表项的值,并将该值插入到输入字段中。如果我在 $("li") 上使用 live("keyup"),则向上/向下箭头键不起作用
  • O 现在我明白了,你有一个列表,你希望向上和向下箭头将 Li 的值返回到 INPUT 标记中......我会做一个小提琴
  • 没问题,你还需要确保你选择了一个答案:)
  • 对不起,我是这个网站的新手。如何选择答案?
  • 在答案的顶部有一个向上和向下的箭头,用于给/尝试答案提供积分或信用,但是要选择正确的答案,在每个答案旁边的积分框下方,您将有一个淡出的刻度按下它,它将变为绿色。
【解决方案3】:

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

The docs are here

我还将向li 添加一个特定的类,以便您可以使用如下选择器:

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

【讨论】:

    【解决方案4】:
    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';
    }
    

    【讨论】:

    • 由于您只发布代码,没有解释,您介意翻译 cmets,因为这是一个英文网站吗?
    猜你喜欢
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2013-07-15
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多