我将自动完成附加到不同类型的输入框。每当用户开始输入任何可以的内容时,它都会加载项目。但是,在其中一个 textarea中,我想默认禁用自动完成功能,并在用户输入“@”时启用它。这该怎么做?
问问题
2859 次
2 回答
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;
}
});
于 2012-07-12T03:04:46.990 回答
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>
于 2020-10-14T07:50:35.873 回答