jQuery UI自动完成的问题

时间:2014-07-17 16:02:22

标签: javascript jquery html jquery-ui autocomplete

我编写了以下代码,在文本框中使用jQuery UI的自动完成方法。

$(function() {
    $('#project').autocomplete({
            source: function(request, response){response(Object.getOwnPropertyNames(projects))},
            minLength: 0,
            messages: {noResults: '', results: function(){}},
            autoFocus: true
        }).on('focus', function(event) { //Display the suggestions list on focus
            $(this).autocomplete("search", "");
        });
})

我面临以下问题:

  1. 点击文本字段时会显示相应的建议列表,但autoFocus不起作用。我想要突出显示列表中的第一个值。但这就是我得到的:enter image description here
  2. 鼠标悬停时,列表元素会突出显示,如下所示:

    enter image description here

    我使用以下样式来完成此任务:

    .ui-autocomplete a:hover {background-color: #C1CDCD;cursor:default}
    

    但是,当我使用向上/向下箭头导航列表时, 相应的值显示在文本字段中但是元素中 列表没有突出显示。

  3. 如何解决这些问题?

    这里是JSFiddel

    感谢您的时间。

1 个答案:

答案 0 :(得分:1)

您可以使用开放和聚焦方法完成所需的操作,然后关闭自动对焦,使其不会突出显示第一个项目。我还使用了一个名为first open的类来允许第一个项目在最初失去焦点时再次突出显示。

代码:

JS FIDDLE

codez:

projects = {Apple: "fruit",Apostle: "Saint"};
$(function () {
    $('#project').autocomplete({
        source: function (request, response) {
            response(Object.getOwnPropertyNames(projects));
        },
        minLength: 0,
        messages: {
            noResults: '',
            results: function () {}
        },
        //autoFocus: true,
        open: function( event, ui ) {
                $('.ui-autocomplete > li:first-child a').addClass('ui-state-focus first_open');
        },
        focus: function( event, ui ) {            
            if(ui.item.value != $('.ui-state-focus').text()){
                $('.first_open').removeClass('ui-state-focus first_open');
            }

       },    
    }).on('focus', function (event) { //Display the suggestions list on focus   
        $(this).autocomplete("search", "");

    });
});