Jquery Add Active Class to Selected List Item on Arrow Key

问题描述 投票:0回答:0

我有一个自动建议文本框,我在其中显示用户键入的建议列表。现在我试图在向下箭头和向上箭头键按下时启用用户选择项。到目前为止,下面是我的代码。当按下向上箭头和向下箭头时,它正在向当前项目添加一个活动类。但问题是在释放密钥后它会立即删除活动类。如我所见,每次释放密钥时都会触发 ajax 成功消息,这会替换整个建议列表。如何解决这个问题

$(document).ready(function() {
    var currentFocus = -1;

    $('#vAccount').keyup(function(event) {
        var searchTerm = $(this).val().toLowerCase();
        if (searchTerm.length < 1) {
            $('#suggestionList').empty();
            currentFocus = -1; // Reset currentFocus when search term is cleared
            return;
        }

        $.ajax({
            url: 'pages/form/ajxpost_get_accounts.php',
            type: 'post',
            data: {
                query: searchTerm
            },
            success: function(data) {
                $('#suggestionList').empty().append(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
    });


    var currentFocus = -1;
    $(document).on('keydown', function(event) {
        if (event.keyCode == 38 || event.keyCode == 40) { // up or down arrow
            var $suggestions = $('#suggestionList li');
            var numSuggestions = $suggestions.length;

            if (currentFocus == -1 && numSuggestions > 0) {
                currentFocus = 0;
                $suggestions.eq(currentFocus).addClass('active');
                return false;
            } else {
                if (event.keyCode == 40) { // down arrow
                    currentFocus++;
                    if (currentFocus >= numSuggestions) {
                        currentFocus = 0;
                    }
                } else if (event.keyCode == 38) { // up arrow
                    currentFocus--;
                    if (currentFocus < 0) {
                        currentFocus = numSuggestions - 1;
                    }
                }
                $suggestions.removeClass('active');
                $suggestions.eq(currentFocus).addClass('active');
                return false;
            }

            event.preventDefault();
        }
    });


    $(document).on('click', '#suggestionList li', function(event) {
        var selectedValue = $(this).text();
        $('#vAccount').val(selectedValue);
        $('#suggestionList').empty();
    });


});

jquery keydown arrow-keys
© www.soinside.com 2019 - 2024. All rights reserved.