Tôi đang sử dụng một <datalist>
Thực hiện hành động khi nhấp HTML5 datalist tùy chọn
<datalist id="items"></datalist>
Và sử dụng AJAX để đưa vào danh sách
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();
}
Tuy nhiên tôi không thể có được nó để thực hiện một hành động khi tôi bấm vào một lựa chọn trong datalist, ví dụ nếu tôi gõ vào "Ref F" và mục "Ref flowers" xuất hiện, nếu tôi click vào nó, tôi cần phải thực hiện một sự kiện.
Làm thế nào tôi có thể làm điều này?
option.addEventListener("click", function() {
option.addEventListener("onclick", function() {
option.addEventListener("change", function() {
Xin vui lòng cung cấp js fiddle của same..I nghĩ rằng bạn đang gắn các sự kiện tại time..You sai cần phải ràng buộc các sự kiện sau khi các phần tử được nối thêm vào DOM .. – Rayon