我正在使用一个 <datalist>
元素。
<datalist id="items"></datalist>
使用 AJAX 来填充列表
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x][0];
option.innerHTML = arr[x][1];
//add each autocomplete option to the 'list'
option.addEventListener("click", function() {
console.log("Test");
});
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
然而,当我在数据列表中点选一个选项时无法触发事件。比如当我输入 "Ref F" 时,如果出现 "Ref flowers" 这个选项,我需要执行一个事件,但是我不知道该怎么做。
option.addEventListener("click", function() {
option.addEventListener("onclick", function() {
option.addEventListener("change", function() {