我将自动完成功能附加到不同类型的输入框。只要用户开始键入任何正常的任何内容,它就会加载项目。但是,在其中一个textarea 中,我想默认禁用自动完成功能,如果用户输入“@”,则启用它。怎么做?
答案 0 :(得分:2)
这样可以解决问题:
$('textarea').autocomplete({
source: availableTags
})
.autocomplete('disable')
.on('keypress', function(event) {
//Detect whether '@' was keyed.
if (event.shiftKey && event.keyCode === 64) {
$(this).autocomplete('enable');
return false;
}
});
答案 1 :(得分:0)
我发现,如果您以'@'开始输入,那么可接受的答案就足够了,但是当'@'嵌入在段落的更深处时,效果不是很好。我仍在努力寻找更好的解决方案,但这是我到目前为止所拥有的。
$(document).ready(function() {
function getCurrentWord(el) {
var $t = $(el),
v = $t.val(),
minLength = $t.data('uiAutocomplete').options.minLength,
start = $t.prop('selectionStart'),
end = $t.prop('selectionEnd'),
re = /(\@[^\s]+)/g,
matches = [], m;
if (start !== end) // user has text highlighted
return false;
while((m = re.exec(v)) != null) {
var endIndex = m.index + m[1].length;
if (start >= m.index && start <= endIndex) {
var result = {
start: m.index,
end: endIndex,
value: m[1]
};
return result.value.length >= minLength && result;
}
}
return false;
}
$('textarea').autocomplete({
minLength: 2,
focus: function() {
// Don't let navigating the menu overwrite textarea value
return false;
},
search: function(event, ui) {
var word = getCurrentWord(this);
if (word) return word.value;
return false;
},
select: function(event, ui) {
var fullValue = ui.item.value;
var target = getCurrentWord(this);
var value = $(this).val();
if (target)
$(this).val(
value.slice(0, target.start)
+ fullValue
+ value.slice(target.end)
);
return false;
},
source: function(req, response) {
var word = getCurrentWord(this.element);
response([
'Adam',
'Alice',
'Bjorn',
'Cathryn',
'Chris',
'David',
'Edward',
'Francis',
'George',
'Hermen',
'Heidi',
'Issac',
'Jennifer',
'Katie',
'Kristen',
'Larry',
'Melinda',
'Nina',
'Oliver',
'Peter',
'Quagmire',
'Rodger',
'Stacey',
'Trevor',
'Ulysses',
'Victor',
'William'
].map(function(s) { return '@' + s; })
.filter(function(s) {
if (!word) return true;
else return s.toLowerCase().startsWith(word.value.toLowerCase());
}));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<textarea></textarea>