2014-07-17 158 views
1

我写了下面的代码,在文本框上使用jQuery UI的自动完成方法。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. 虽然点击文本字段确实显示的建议对应的列表,自动对焦不起作用。我想要突出显示列表中的第一个值。但是,这是我得到的:enter image description here
  2. 在鼠标悬停时,列表元素,会突出显示,像这样:

    enter image description here

    我用下面的样式来实现:

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

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

如何解决这些问题?

这是JSFiddel

谢谢你的时间。

+0

你能发布的jsfiddle?似乎有2个简单的CSS规则可以实现这一点。 – Rooster

+0

@Rooster:会做 – raul

+0

@Rooster:刚刚添加小提琴的问题 – raul

回答

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", ""); 

    }); 
}); 
+0

像魔术一样工作!尽管我不太了解新代码 – raul

+1

,所以当建议打开时,列表中的第一项获得类first_open以及ui-state-focus,这是自动建议用于突出显示的内容。然后一个项目被聚焦,'ui-state-focus'类需要从第一个项目中移除,但是只有第一次焦点被改变。多数民众赞成在这两种方法发生了什么。 – Rooster