2016-07-05 74 views
1

我使用手机的标签/值列表jQuery的自动完成:当用户jQuery的自动完成 - 在价值和显示标签搜索

[ { label: "Samsung Galaxy S7", value: "Samsung Galaxy S7"}, 
    { label: "Samsung Galaxy S6", value: "Samsung Galaxy S6"}, 
..... 
] 

我想没有specifing系列名称进行研究,即类型“三星S7”自动完成建议“三星Galaxy S7”

我试图修改源如下:

[ { label: "Samsung Galaxy S7 Samsung S7", value: "Samsung Galaxy S7"}, 
    { label: "Samsung Galaxy S6 Samsung S6", value: "Samsung Galaxy S6"}, 
..... 
] 

此代码的作品,但它是丑陋的,因为一个utocomplete菜单显示“三星Galaxy S6三星S6”,而不是一个简单的“三星Galaxy S6”

有没有办法对一个属性进行研究,而在菜单中显示不同的?

回答

2

您需要使用source选项编写自定义搜索逻辑。对于一个简单的用例,下面的内容可以做到。有关更多信息,请参阅jQuery UI Autocomplete widget search configuration

也许你需要一个复杂的正则表达式来处理边缘情况(如果你有一个静态/可信任的数据源,则不需要)。

$(document).ready(function() { 
 

 
    var devices = [{ 
 
    label: "Samsung Galaxy S7", 
 
    value: "Samsung Galaxy S7" 
 
    }, { 
 
    label: "Samsung Galaxy S6", 
 
    value: "Samsung Galaxy S6" 
 
    }]; 
 

 
    $("#devices").autocomplete({ 
 
    source: function(req, responseFn) { 
 
     var words = req.term.split(' '); 
 
     var results = $.grep(devices, function(device, index) { 
 
     var sentence = device.label.toLowerCase(); 
 
     return words.every(function(word) { 
 
      return sentence.indexOf(word.toLowerCase()) >= 0; 
 
     }); 
 
     }); 
 
     responseFn(results); 
 
    } 
 
    }); 
 

 
});
input { 
 
    margin-top: 100px; 
 
}
<link href="https://code.jquery.com/ui/1.8.23/themes/smoothness/jquery-ui.css" rel="stylesheet" /> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script> 
 
<input type="text" id="devices" />

+0

它工作正常,谢谢! 我没有看到将函数定义为允许执行自定义搜索的源 – gbalduzzi

相关问题