さまざまな種類の入力ボックスにオートコンプリートをアタッチしています。ユーザーが問題のないものを入力し始めるたびにアイテムをロードします。しかし、テキストエリアの1つで、デフォルトでオートコンプリートを無効にし、ユーザーが「@」と入力すると有効にします。これを行う方法?
質問する
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 に答える