我在Stackoverflow找到了完美的解决方案。此代码检测@标签,而不是自定义单词的自动完成程序。
jQuery(function(){
function getCaretPosition(e) {
if (typeof e.selectionStart == 'number') {
return e.selectionStart;
} else if (document.selection) {
var range = document.selection.createRange();
var rangeLength = range.text.length;
range.moveStart('character', -e.value.length);
return range.text.length - rangeLength;
}
}
function setCaretPosition(e, start, end) {
if (e.createTextRange) {
var r = e.createTextRange();
r.moveStart('character', start);
r.moveEnd('character', (end || start));
r.select();
} else if (e.selectionStart) {
e.focus();
e.setSelectionRange(start, (end || start));
}
}
function getWordBeforeCaretPosition(e) {
var s = e.value;
var i = getCaretPosition(e) - 1;
while (i >= 0 && s[i] != ' ') {
i = i - 1;
}
return i + 1;
}
function getWordBeforeCaret(e) {
var p = getWordBeforeCaretPosition(e);
var c = getCaretPosition(e);
return e.value.substring(p, c);
}
function replaceWordBeforeCaret(e, word) {
var p = getWordBeforeCaretPosition(e);
var c = getCaretPosition(e);
e.value = e.value.substring(0, p) + word + e.value.substring(c);
setCaretPosition(e, p + word.length);
}
jQuery("#"+commentAreaId).bind("keydown", function(event){
if (event.keyCode === jQuery.ui.keyCode.TAB && jQuery(this).data("autocomplete").menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function(request, response) {
var w = getWordBeforeCaret(this.element[0]);
if (w[0] != '@') {
this.close();
return false;
}
response(jQuery.ui.autocomplete.filter(completerData, w.substring(1, w.length)));
return true;
},
focus: function() {
return false;
},
search: function(event, ui) {
return true;
},
select: function(event, ui) {
replaceWordBeforeCaret(this, ui.item.label + '|' + ui.item.value );
return false;
}
});
});
但我不明白,如何通过JSON使其与远程数据源一起工作。 还有更清洁和完美的实现吗? 感谢