使用javascript,如何从自动完成列表中选择点击的项目?

时间:2018-01-28 09:35:25

标签: javascript ajax

我想用普通的Javascript而不是jQuery来做这件事。我有一个脚本,它根据keyup事件进行ajax调用并返回一个更改的项目列表。因此,在搜索框中输入3个字符(" eth")后,我们可能会有这样的列表:

ethereum
ethereum-classic
ethos
ethlend
etherparty
etheroll
ethereum-blue
ethorse
ethbits
etheriya
ethereumcash
ethbet
ethereum-gold
ethereum-dark
ethereum-movie-venture
ethgas
etherdelta-token
ethereum-lite

现在我想通过点击它从列表中选择一个项目。到目前为止的代码是:

function loadDoc() {
        var string = document.getElementById("searchbox").value;
        var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
             document.getElementById("demo").style.display = "";
             document.getElementById("demo").innerHTML = "";
       obj = JSON.parse(this.responseText);
             for (i = 0; i < obj.length; i++) {
           document.getElementById("demo").innerHTML += "<div>" + obj[i].id + "</div>";
                        }
                        document.getElementById("demo").addEventListener("click", "div", function(){
                        var item = document.getElementById('demo').innerHTML;
                        //var item = this.getElementById("demo")[0].innerHTML;
               alert(item);
             });
      }
    };
    xhttp.open("POST", "/search?string=" + string, true);
    xhttp.send();

除了行

之外,一切正常
document.getElementById("demo").addEventListener("click", "div", function(){
                            var item = document.getElementById('demo').innerHTML;
                            //var item = this.getElementById("demo")[0].innerHTML;

我尝试了多种变体,我所取得的最好的是点击事件捕获整个列表,我希望点击的项目是唯一返回的项目。使用Javascript实现此目的的正确方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

您错误地定义addEventListener,回调函数必须是第二个参数。然后,您可以使用event.target来访问所点击的项目。以下是示例代码:

&#13;
&#13;
<div id="demo">demo</div>

<script>
  //assume you get all items in this obj
  var obj = [{id:"ethereum"}, {id:"ethereum-classic"}, {id:"ethos"}, {id:"ethlend"}, {id:"etherparty"}] //...

  document.getElementById("demo").innerHTML = "";

  for (i = 0; i < obj.length; i++) {
      document.getElementById("demo").innerHTML += "<div>" + obj[i].id + "</div>";
  }
  
  document.getElementById("demo").addEventListener("click", function(e){
      var item = e.target; //event.target
      alert(item.innerText); //get text of selected item (eg "ethereum")
  }); 
</script>
&#13;
&#13;
&#13;