Skip to content

Instantly share code, notes, and snippets.

@gai00
Created August 29, 2019 07:29
Show Gist options
  • Select an option

  • Save gai00/91b42e05332ad989ab3756f9d83c1858 to your computer and use it in GitHub Desktop.

Select an option

Save gai00/91b42e05332ad989ab3756f9d83c1858 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="searchText" placeholder="search" list="searchList" />
<datalist id="searchList">
<select></select>
</datalist>
<script type="text/javascript">
var searchText = document.getElementById("searchText");
var searchList = document.getElementById("searchList");
window.addEventListener("load", function() {
console.log("ok");
searchText.focus();
});
// 清空
function clean() {
while(searchList.firstChild) {
searchList.removeChild(searchList.firstChild);
}
}
var timer = null;
var typing = false;
var onced = true;
var tempResult = null;
searchText.addEventListener("compositionstart", function(e) {
typing = true;
});
searchText.addEventListener("compositionupdate", function(e) {
typing = true;
});
searchText.addEventListener("compositionend", function(e) {
typing = false;
if(!onced) {
clean();
searchList.appendChild(tempResult);
}
onced = true;
});
searchText.addEventListener("input", function(e) {
if(timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
var value = e.target.value;
console.log(value);
var newSelect = document.createElement("select");
for(var i = 0; i < 10; i += 1) {
var newOption = document.createElement("option");
newOption.value = value + "[" + i + "]";
newSelect.appendChild(newOption);
}
if(onced) {
clean();
searchList.appendChild(newSelect);
}
else {
tempResult = newSelect;
}
timer = null;
}, 300);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment