JQuery - 将 Enter KeyPress 事件附加到列表项

发布于 2024-11-16 08:44:23 字数 418 浏览 0 评论 0原文

我正在用 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
        }
    });
}

I'm writing my own autocomplete plugin with jquery. The list items are drawn dynamically based on a json response. I have up/down arrow key code that works well on keyup event fired on the input field.

I want to add an enter key event to every list item. So, when the user is navigating through the autocomplete dropdown using the up/down arrow keys, an enter key press event would add the value of that list item to the input field.

Can someone please help? I've tried binding event to the list item

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

老街孤人 2024-11-23 08:44:23

您不能只使用绑定,因为在评估 javascript 时列表项不在 DOM 中。

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

如果您有

  • ...
  • 那么您可以调用实时事件,如下所示:

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

    You can't use just bind, because the list items aren't in the DOM when that javascript is evaluated.

    Look into using jQuery.live() http://api.jquery.com/live/

    If you have <div id='autocomplete'><li>...</li></div> then you could call the live event like:

    $("#autocomplete li").live("keyup", function(e) {
        if (e.keyCode == 40)
            // Add to the input field
    });
    
    此岸叶落 2024-11-23 08:44:23

    像这样的事情:

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

    要在这里扩展您的评论,请使用 jfiddle http://jsfiddle.net/csLVX/5/< /a>: {稍微整理一下我的代码!}

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

    Something like this:

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

    To expand on your comment here is a jfiddle http://jsfiddle.net/csLVX/5/: {tidying up my code a bit!}

        <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
        } 
    }); 
    
    ╰沐子 2024-11-23 08:44:23

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

    文档在这里

    我还会向 li' 添加一个特定的类因此您可以使用如下选择器:

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

    You probably want to use live() rather than bind() so that it works even when your li's are dynamically loaded.

    The docs are here

    I would also add a specific class to the li's so you can use a selector like:

    $('.my_loaded_selection').live('keyup', function(e){//do your thing
    }) ;
    
    白龙吟 2024-11-23 08:44:23
    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';
    }
    
    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';
    }
    
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文