【问题标题】:How should I adjust my code to create an autocomplete that start with first letter?我应该如何调整我的代码以创建以第一个字母开头的自动完成?
【发布时间】:2016-11-17 23:35:51
【问题描述】:

我正在尝试创建一个自动完成搜索框。
它可以工作,但这里有一个问题是,当用户在搜索框中键入时,它不会以第一个字母开头。
如果我在搜索框中输入第一个字母,它将显示所有包含该字母的单词,但我只希望它显示以该字母开头的单词。
我该怎么办?我发现这是在 Firefox 中发生的,但在 chrome 中是可以的。

var dataList = document.getElementById("auto_json_datalist");
 // Create a new XMLHttpRequest.
var request = new XMLHttpRequest();
 // Handle state changes for the request.
request.onreadystatechange = function(response) {
  if (request.readyState === 4) {
    if (request.status === 200) {
      // Parse the JSON
      var jsonOptions = JSON.parse(request.responseText);
      // Loop over the JSON array.
      jsonOptions.forEach(function(item) {
        // Create a new <option> element.
        var option = document.createElement("option");
        // Set the value using the item in the JSON array.
        option.value = item;
        // Add the <option> element to the <datalist>.
        dataList.appendChild(option);
      });
    } else {
      // An error occured :(
    }
  }
};
 // Set up and make the request.
request.open("GET", "autocompleteSym.json", true);
request.send();
<datalist id="auto_json_datalist"></datalist>
<input type="text"  class="enter_sym_c" list="auto_json_datalist" value="" />

【问题讨论】:

  • 为项目添加检查以查看它是否以 f 开头,如果不是则返回,如果是则将其添加为选项。
  • 如何查看商品?如果用户输入“ap”,那么它应该只显示以“ap”开头的单词。

标签: javascript json ajax autocomplete html-datalist


【解决方案1】:

这只需要一个非常简单的if 条件,它检查输入值的第一个字母,看它是否等于当前项的第一个字母。
如果此条件失败,它将跳过创建 option 元素。

if 条件如下所示:

if(inputBox.getAttribute("value").charAt(0) == item.charAt(0)) {}

if 条件通过使用String.prototype.charAt(...); 函数获取字符串的第一个字母,并提供0 作为第一个(也是唯一一个)参数。
如果您不知道String.prototype.charAt(...); 是什么,或者您想了解更多信息,您应该阅读this MDN 文章。

error item.charAt is not a function 问题是因为jsonOptions.forEach 中的参数(函数)接受两个参数(不是一个)。
这些参数是:indexvalueindex 参数的类型是 number NOT string
没有发现问题是我的错,对此我深表歉意。

幸运的是,解决方案非常简单?我们只是改变了这个:

jsonOptions.forEach(function(item) {

到这里:

// "i" stands for "index"
jsonOptions.forEach(function(i, item) {

我已经纠正了这个问题,这里是编辑后的 ​​JavaScript:

// Sorry for using "document.querySelector" I was far too lazy to use anything else :)
var dataList = document.querySelector("#auto_json_datalist");
var inputBox = document.querySelector(".enter_sym_i");
// Create a new XMLHttpRequest.
var request = new XMLHttpRequest();
// Handle state changes for the request.
request.onreadystatechange = function(response) {
  if (request.readyState === 4) {
    if (request.status === 200) {
      // Parse the JSON
      var jsonOptions = JSON.parse(request.responseText);
      // Loop over the JSON array.
      // The function inside "forEach" accepts two arguments, "index" and "value".
      // The problem was that the "index" argument is a "integer" NOT a string.
      jsonOptions.forEach(function(index, value) {
        // !! This is the if condition that checks the first character of the input value
        if(inputBox.getAttribute("value").charAt(0) == value.charAt(0)) {
          // Create a new <option> element.
          var option = document.createElement("option");
          // Set the value using the item in the JSON array.
          option.setAttribute("value", value);
          // Add the <option> element to the <datalist>.
          dataList.appendChild(option);
        }
      });
    } else {
      // An error occured :(
    }
  }
};
// Set up and make the request.
request.open("GET", "autocompleteSym.json", true);
request.send();

注意:请记住,使用element.getAttribute("...");element.setAttribute("...", "..."); 设置和获取属性以及处理DOM “按原样”( IE:仅处理文字),而不是使用属性。
如果您想了解更多信息,请查看this 问题。

祝你好运,万事如意。

【讨论】:

  • 感谢您的回复,但我收到错误 item.charAt is not a function。
  • @conan 是 item 一个字符串吗?如果item的类型是什么?
  • @conan 我想我知道出了什么问题,我已经编辑了我的答案。
【解决方案2】:

在这里,尝试添加这些更改:

var SUCCESS_CODE = 200,
  NEEDED_REQUEST_STATE = 4,
  dataList = document.getElementById("auto_json_datalist"),
  enteredData = document.getElementsByClassName("enter_sym_c")[0],
  // the data entered by the user
  request = new XMLHttpRequest();

// Handle state changes for the request.
request.onreadystatechange = function(response) {
  if (request.readyState === NEEDED_REQUEST_STATE) {
    if (request.status === SUCCESS_CODE) {
      // Parse the JSON
      parseJSONOptions(request.responseText);
    } else {
      // An error occured :(
    }
  }
};

function parseJSONOptions(data) {
  var jsonOptions = JSON.parse(data);
  jsonOptions.forEach(function(item) {
    var itemString = new String(item["key"]); // you must know what is the key
    if (itemString.startsWith(enteredData.value)) {
      createOption(dataList, item);
    }
  });
}

function createOption(parent, value) {
  // Create a new <option> element.
  var option = document.createElement("option");
  // Set the value using the item in the JSON array.
  option.value = value;
  // Add the <option> element to the <datalist>.
  parent.appendChild(option);
}

// Set up and make the request.
request.open("GET", "autocompleteSym.json", true);
request.send();

您只需要获取已在输入中输入的字符串部分,并且当您获得可能的选项时 - 检查每个选项,如果它以给定的子字符串开头并将其添加到列表中,如果这是真的。

此解决方案还涵盖 2 个字符、3 个字符等情况。

【讨论】:

  • 你应该解释你做了什么,这样 OP 才真正知道下次要做什么。
  • 我的意思是,在这种情况下,代码很容易解释。
  • 感谢您的回复,但我收到错误 item.startsWith 不是函数。
  • 为了使startsWith 工作,对象必须是字符串,因此您可以从item 中创建一个字符串来解决此问题。查看我的编辑。
  • 还是一样的错误 item.startsWith 不是函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 2021-08-30
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
相关资源
最近更新 更多