我正在尝试使用jQuery自动完成在textarea中基于触发器自动完成. (当您键入“@”时,自动完成开始).
到目前为止,我能够在数据是数组的情况下实现它.
<textarea class="searchBox" rows="10" cols="20"></textarea>
jQuery的
var triggered = false; // By default trigger is off
var trigger = "#"; // Defining the trigger
$(".searchBox").autocomplete({
source: [ // defining the source
"A",
"Apple",
"S",
"D",
"q"],
search: function () { // before search, if not triggerred, don't search
if (!triggered) {
return false;
}
},
select: function (event, ui) { // invokes the data source, search starts
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) + ui.item.value;
triggered = false;
return false;
},
focus: function (event, ui) {
return false;
},
minLength: 0 // minimum length of 0 require to invoke search
});
$('.searchBox').keyup(function (e) {
if (e.keyCode == 38 || e.keyCode == 40) {
return;
}
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
} else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
这是它的小提琴:http://jsfiddle.net/5x9ZR/4/
现在我试图在数据采用json对象的形式时实现它.
但是自动完成功能没有响应结果.
我试了一下. (没有任何触发机制).它没有显示任何结果.
码:
HTML
<textarea class="searchBox" rows="10" cols="20"></textarea>
jQuery的
var triggered = false; // By default trigger is off
var trigger = "#"; // Defining the trigger
var data = [{
"name": "needmoreinfo",
"email": "needmoreinfo"
}, {
"name": "explained",
"email": "explained"
}, {
"name": "raypipeline09",
"email": "raypipeline09"
}];
$(".searchBox").autocomplete({
source: data,
search: function () { // before search, if not triggred, don't search
if (!triggered) {
return false;
}
},
select: function (event, ui) { // invokes the data source, search starts
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) + ui.item.email;
triggered = false;
return false;
},
focus: function () {
return false;
},
minLength: 0 // minimum length of 0 require to invoke search
})._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
$('.searchBox').keyup(function (e) {
if (e.keyCode == 38 || e.keyCode == 40) {
return;
}
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
} else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
这是我尝试过的小提琴. http://jsfiddle.net/HGxSX/
我哪里错了?请解释.
最佳答案 解决了它.
由于这种情况发生,jQuery中存在一个错误.
数据必须采用“标签”和“价值”的形式.否则它不起作用.
感谢任何尝试过的人.
这是最后的工作小提琴:http://jsbin.com/qakefini/7
PS:我试过在jQuery网站上开帐,但无法登录.它说一些重定向问题.如果有人有帐户,请报告错误.