0

我正在尝试创建一个自动建议框。当用户开始在#tagSelection 输入字段中输入内容时,JQuery 通过 Ajax 从数据库中获取建议,并将这些建议显示在显示在 #tagSelection 字段正下方的#suggestBox div 中。

现在我想让用户使用向下箭头键来选择其中一个建议。我已经开始通过处理 keydown() 事件并在此事件期间为第一个条目分配一个类来构建它。我面临的问题是,当我放开向下箭头键时,该类又被删除了。当我放开钥匙时,我需要它保持分配状态。那可能吗?

的HTML

<div class="form-entry">
    <input id="tagSelection" name="tags" type="text" value="" size="40">

    <div id="suggestBox" style="">
        <a href="#" id="1">design</a>
        <a href="#" id="3">debit card</a>
        <a href="#" id="4">deer</a>
    &nbsp;
    <a href="#" id="addTag">Add word</a>

    <div id="selectedTags"></div>

</div>

jQuery

(function() {
    $('#tagSelection').keydown(downArrowKeyHandler);
})();

function downArrowKeyHandler(event) {
    if (event.keyCode == 40) {
        if ($('#suggestBox').length > 0) {
            if ($('[tagSelected = 1]').length == 0) {
                // the tagSelected class gives the entry a colored background
                $('#suggestBox').children().filter(':first').addClass('tagSelected');
            }
        }
    }
}
4

3 回答 3

1

如果我说对了,在这种情况下,Jquery 自动完成就足够了。试试这个演示

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input class="ui-widget ui-widget-content ui-corner-all" id="tags">
</div>

$( "#tags" ).autocomplete({
    source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "python", "c", "scala", "groovy", "haskell", "perl" ],
    delay: 0
});
于 2012-12-25T13:35:03.297 回答
1

JS代码:

$("input").keypress( function() {
var s = $(this).val();
$.ajax({
other params
success: function(data) { // here data contains all the suggest echoed with comma seprated (see below)
var s = data.split(",");
$(this).autocomplete({
    source: s,
    delay: 0
});
});
});

In PHP It should be echoed like this

siren,sam,sami,salman
于 2012-12-25T13:45:19.360 回答
0

I found the exact same problem here:

How to make a permanent change to an element after using jQuery's .keydown()?

It seems I indeed had some other JQuery code that was interfering with my event handler. Whenever someone releases a key when in the #tagSelection field a JQuery method fires that retrieves the suggestions from the db. The already present keyup() event was interfering with my new keydown() event.

(function() {
    $('#tagSelection').keyup(tagboxTypingHandler)
})();


function tagboxTypingHandler(event) {
    if (event.keyCode != 40) {
        var substring = $('#tagSelection').val();
        if (substring.length > 1) {
            $.get("http://localhost:8080/tag/search/" + substring, returnedTagsHandler);
        }
    }
}

I just added the event.keyCode != 40 condition and now the class remains on the suggestion and it works :-)

于 2012-12-25T13:45:21.413 回答