Javascript自动完成下拉功能混淆

我正在使用这个W3C Schools 自动完成下拉菜单。


function autocomplete(inp, arr) {

  /*the autocomplete function takes two arguments,

  the text field element and an array of possible autocompleted values:*/

  var currentFocus;

  /*execute a function when someone writes in the text field:*/

  inp.addEventListener("input", function(e) {

      var a, b, i, val = this.value;

      /*close any already open lists of autocompleted values*/

      closeAllLists();

      if (!val) { return false;}

      currentFocus = -1;

      /*create a DIV element that will contain the items (values):*/

      a = document.createElement("DIV");

      a.setAttribute("id", this.id + "autocomplete-list");

      a.setAttribute("class", "autocomplete-items");

      /*append the DIV element as a child of the autocomplete container:*/

      this.parentNode.appendChild(a);

      /*for each item in the array...*/

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

        /*check if the item starts with the same letters as the text field value:*/

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

          /*create a DIV element for each matching element:*/

          b = document.createElement("DIV");

          /*make the matching letters bold:*/

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

          b.innerHTML += arr[i].substr(val.length);

          /*insert a input field that will hold the current array item's value:*/

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

          });

          a.appendChild(b);

        }

      }

  });

我对这个自动完成功能中的这行代码感到困惑:


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

this上面的代码指的是什么?


我们为什么要这样做this.getElementsByTagName("input")[0]?


我正进入(状态:


未捕获的类型错误:无法读取未定义的属性“值”


在这一行。然而,我确实修改了上面的函数并删除了inp参数上的添加事件侦听器行。


慕标琳琳
浏览 177回答 3
3回答

慕慕森

让我们一步一步地打破这个问题。您没有从 w3school 复制完整的脚本,请复制它,因为与上述代码相关的“addEventListener”、“addActive”等函数很少。inp.value = this.getElementsByTagName("input")[0].value;&nbsp;这里this指的是文档(window.document)this.getElementsByTagName("input")[0]&nbsp;如果我们不写它,我们将得到未定义,因为在这里您将搜索的项目分配给搜索输入框中的第一个元素。

慕婉清6462132

如果您可以看到代码,您会发现当用户开始在输入字段上输入时,会出现一个包含建议的列表。当用户单击任何建议选项时,该值被设置为文本框。所以在这里,在建议列表中,选项是这样生成的<div>&nbsp; &nbsp;<strong>A</strong>&nbsp; &nbsp;fghanistan&nbsp; &nbsp;<input type="hidden" value="Afghanistan"></div>我们在这个 div 元素上点击了监听器,你可以在它下面找到这个代码this.getElementsByTagName 返回具有给定标签名称的元素的集合码this.getElementsByTagName("input")[0]与标签名称搜索元件input下this(这是当前的div)。[0]这是在返回的集合中的第一个查找,因此它找到具有 value 的输入元素Afganistan。哪个被设置为文本框值。

四季花海

正如您在下面的代码段中看到的,this关键字引用(内部处理程序)到输入元素本身。代码的作者使用this.getElementsByTagName("input")[0](但不清楚为什么以这种方式)可能是因为他想从其他输入复制值 - 但是您可以在不使用它的情况下设置该值(例如直接方式inp.value='some autocompleted vale',取决于您的情况)inp.addEventListener("input", function(e) {&nbsp; console.log(this.value, this);})<input id="inp" placeholder='type here'>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript