我有一个用于搜索的文本字段,我正在尝试添加功能以向用户显示在键入时输入的先前搜索。我希望它的功能类似于jQuery自动完成如何与文本框下方显示的列表一起使用。我想知道是否内置了HTML选项,我可以实现这一点。谢谢。
答案 0 :(得分:1)
这是一个五分钟的尝试。使用cookie存储搜索(here's the code and the demo):
我在jQueryUI文档页面上使用了autocomplete demo的代码,并用一系列cvs分隔值替换原始数组(在逗号分隔的第二个时刻)来重新创建数组。
// this func return cookie of name 'cname'
// if you use _searches as prameter you'll get a csv (i.e.: valeu1,value2...) containing the words searched
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
// this function adds value to '_searches' cookie
function search() {
var s = getCookie('_searches');
document.cookie = "_searches="+s+','+$("#search").val();
}
这里发生了神奇的事情,你可以在数组中形成一个适合jQueryUI自动完成的csv:
var availableTags = getCookie('_searches').split(',');
这是一个五分钟的尝试,需要很多改进,顺便说一下。
答案 1 :(得分:1)
尝试
$(function () {
var _source = [];
$("#dynsearch")
.autocomplete({
// update `source` with `value` of `#dynsearch` ,
// on `change` event
change: function (event, ui) {
// insert `#dynsearch` `value` into `_search` (`source`) array
_source.splice(0, 0, event.target.value);
event.target.value = "";
},
source: _source
});
});
$(function () {
var _source = [];
$("#dynsearch")
.autocomplete({
change: function (event, ui) {
_source.splice(0, 0, event.target.value);
event.target.value = "";
},
source: _source
})
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<div class="ui-widget">
<label for="dynsearch">search:</label>
<input id="dynsearch" />
</div>
&#13;