我正在使用 <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() {
最佳答案
很抱歉挖掘这个问题,但我遇到了类似的问题并且有一个解决方案,它应该也适合你。
function onInput() {
var val = document.getElementById("input").value;
var opts = document.getElementById('dlist').childNodes;
for (var i = 0; i < opts.length; i++) {
if (opts[i].value === val) {
// An item was selected from the list!
// yourCallbackHere()
alert(opts[i].value);
break;
}
}
}
<input type='text' oninput='onInput()' id='input' list='dlist' />
<datalist id='dlist'>
<option value='Value1'>Text1</option>
<option value='Value2'>Text2</option>
</datalist>
此解决方案源自 Stephan Mullers 解决方案。它也应该与动态填充的数据列表一起使用。
遗憾的是,无法判断用户是单击了数据列表中的某个项目,还是通过按 tab 键选择了它,还是手动键入了整个字符串。
关于javascript - 单击 HTML5 数据列表选项时执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30022728/