搜索栏中的自动完成:具有相同用户名的不同用户

omvjsjqw  于 2021-06-21  发布在  Mysql
关注(0)|答案(0)|浏览(225)

我正在创建一个社交媒体平台,遇到了这个我无法解决的问题。我有一个数据库表users有用户名和email(email对每个人都是不同的)。但是,用户可以有相同的用户名。当我通过搜索栏中的autocomplete搜索一个用户时,它会显示所有的用户名以及我搜索过的特定起始字符串。现在我想,当我点击一个特定的用户名,他的个人资料应该打开。但也有相同用户名的人。我该怎么做呢。
需要注意的几点:
我正在创建一个用户名数组,并将该数组传递给js供autocomplete使用。
每个用户都会附加一个自动递增的id
下面是自动完成的脚本:

function autocomplete(inp, arr) {

  var currentFocus;

  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;

      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;

      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");

      this.parentNode.appendChild(a);

      for (i = 0; i < arr.length; i++) {

        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {

          b = document.createElement("DIV");

          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);

          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";

          b.addEventListener("click", function(e) {

              inp.value = this.getElementsByTagName("input")[0].value;

              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });

  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {

        currentFocus++;

        addActive(x);
      } else if (e.keyCode == 38) { //up

        currentFocus--;

        addActive(x);
      } else if (e.keyCode == 13) {

        e.preventDefault();
        if (currentFocus > -1) {

          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {   
    if (!x) return false;    
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);

    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {

    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {   
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    }
  } 
  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
      });
}

var user_names = <?php echo json_encode($names) ;?>
autocomplete(document.getElementById("myInput"), user_names);

用户名:它是我从php文件中获得的用户名数组

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题