不仅在开始时自动完成文本的中间部分



有没有一种方法可以在文本中间实现自定义自动完成列表,而不仅仅是从一开始?

比方说,我有一个像这样的自定义自动完成列表。

['@Martin','@Josu','@Mikenko','@Buarandun','@Ravindran','Basix','#ItemNr']

当我在输入中键入以下内容'Hallo @M'时,它应该列出['@Martin' ,'@Mikenko']

https://www.w3schools.com/howto/howto_js_autocomplete.asp

谢谢。

const searchInput = document.getElementById("search");
const output = document.getElementById("output");
const names = [
"@Martin",
"@Josu",
"@Mikenko",
"@Buarandun",
"@Ravindran",
"Basix",
"#ItemNr"
];
searchInput.addEventListener("input", matchNames);
function matchNames(e) {
const { value } = e.target;
output.innerHTML = ""
// start matching if '@' symbol found
if (value.includes("@")) {
const symbolIndex = value.indexOf("@"); // get the symbol index
const matchValue = value.substring(symbolIndex); // start matching from symbol index
const matchList = names.filter(
name => name.toLowerCase().indexOf(matchValue.toLowerCase()) !== -1
);
// output
const html = matchList.map(name => {
const Name = name
.toLowerCase()
.replace(matchValue, `<strong>${matchValue}</strong>`)
return `<span class="name">${Name}</span>`
}).join("")
// push data into output
output.innerHTML = html
}
}
.name {
display: block
}
<input id="search" type="text" class="form-control" placeholder="names">
<div id="output"></div>

本部分

inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;

转换为

inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
val = val.split(' ').reverse()[0];   // Get last 

这应该得到最后的话总是

您可以根据要启动自动完成的字符长度应用条件。例如,你可以说

if(yourInput.length > 3 ) {
//your rest autocomplete thing here
}

您可以使用search()方法。请在此处阅读。

后的更改

if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {

if (val.toUpperCase().search(arr[i].toUpperCase()) != -1) {

未测试,希望这有帮助:(

您只需要更改

var a, b, i, val = this.value.split("@");
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val || val.length < 2) { return false;}
val = val[val.length-1]

然后

if(arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase())

if(arr[i].toLowerCase().indexOf(val.toLowerCase()) !== -1)

以及显示列表的更改

b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);

b.innerHTML = arr[i].toLowerCase().replace(val.toLowerCase(), '<b>' + val.toLowerCase() + '</b>');
b.style.textTransform = "capitalize";

当您刚在文本中键入"@"时,它将开始显示自动完成。

示例代码笔

最新更新