javascript 更改自动完成功能

6jjcrrmo  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(83)

我真的很喜欢自动完成功能,但有没有可能改变它,所以它是空白的,当我按下里面的文本框,只有显示国家,当我开始键入的东西?我不知道我应该怎么做,所以如果有人能告诉/告诉我在哪里解决这个问题,我会很感激。

当我开始键入一些东西,如“Alb”,然后删除此并单击文本框外部,然后再次单击它内部,以前的结果仍然存在
代码片段

// Sample list of autocomplete options
var countries = [
  "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan",
  "The Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia",
  "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi"
];

// Get references to the input field and the dropdown list
var input = document.getElementById("country-name");
var autocompleteList = document.getElementById("suggestion-list");

// Function to display the dropdown list
function showAutocompleteList() {
  autocompleteList.style.display = 'block';
}

// Function to hide the dropdown list
function hideAutocompleteList() {
  autocompleteList.style.display = 'none';
}

// Event listener for input field
input.addEventListener("input", function() {
  var inputValue = input.value;
  autocompleteList.innerHTML = '';

  // Filter and display matching items
  countries.forEach(function(country) {
    if (country.toLowerCase().startsWith(inputValue.toLowerCase())) {
      var item = document.createElement("li");
      item.textContent = country;
      item.classList.add("autocomplete-item"); // Add the "autocomplete-item" class
      item.addEventListener("click", function() {
        input.value = country;
        autocompleteList.innerHTML = '';
      });
      item.addEventListener("mouseenter", function() {
        item.classList.add("active"); // Add the "active" class on hover
      });
      item.addEventListener("mouseleave", function() {
        item.classList.remove("active"); // Remove the "active" class when not hovering
      });
      autocompleteList.appendChild(item);
    }
  });

  showAutocompleteList(); // Display the list when input changes
});

// Event listener for "keydown" on the input field
input.addEventListener("keydown", function(e) {
  if (e.key === "Tab") {
    e.preventDefault(); // Prevent the default tab behavior

    // Handle the Tab key behavior for selecting an item
    var activeItem = autocompleteList.querySelector(".autocomplete-item.active");
    if (activeItem) {
      input.value = activeItem.textContent;
      autocompleteList.innerHTML = '';

      // Redirect to the corresponding HTML page
      var countryUrl = 'Countries/' + activeItem.textContent.toLowerCase() + '.html';
      window.location.href = countryUrl;
    }
  }
});

// Event listener for clicking on the list items
autocompleteList.addEventListener("click", function(e) {
  if (e.target.classList.contains("autocomplete-item")) {
    // If the clicked element has the "autocomplete-item" class
    input.value = e.target.textContent;
    // Redirect to the corresponding HTML page
    var countryUrl = 'Countries/' + e.target.textContent.toLowerCase() + '.html';
    window.location.href = countryUrl;
    e.preventDefault(); // Prevent the default click behavior
  }
});

// Event listener to close the dropdown when clicking outside of the input field
document.addEventListener("click", function(e) {
  if (e.target !== autocompleteList && e.target !== input) {
    hideAutocompleteList();
  }
});

// Event listener for clicking inside the input field to display the dropdown
input.addEventListener("click", showAutocompleteList);
<header>
  <h1>Select a country</h1>
</header>
<main>
  <div id="content-wrapper">
    <div id="get-container">
      <input type="text" id="country-name" placeholder="Enter a country" autocomplete="off">
      <div id="suggestion-list" class="autocomplete-items"></div>

      <div id="error-message"></div>
    </div>
    <div id="story-container">
      <div id="generated-text"></div>
      <button id="clear">Clear</button>
    </div>
  </div>
</main>
laawzig2

laawzig21#

1.添加了focus事件侦听器,用于在单击输入字段时清除列表。
1.更新了showAutocompleteList()函数,仅在输入值不为空时显示列表。
1.更新了输入的input事件侦听器,以仅在输入至少包含一个字符时过滤和显示列表。
1.修改了输入的keydown事件侦听器,以便在显示列表之前检查输入值的长度。

var countries = [
  "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan",
  "The Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia",
  "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi"
];

// Get references to the input field and the dropdown list
var input = document.getElementById("country-name");
var autocompleteList = document.getElementById("suggestion-list");

// Function to display the dropdown list
function showAutocompleteList() {
  if (input.value !== '') {
    autocompleteList.style.display = 'block';
  }
}

// Function to hide the dropdown list
function hideAutocompleteList() {
  autocompleteList.style.display = 'none';
}

// Event listener for input field
input.addEventListener("input", function() {
  var inputValue = input.value;
  autocompleteList.innerHTML = '';

  // Only filter and display the list if there is at least one character
  if (inputValue.length > 0) {
    countries.forEach(function(country) {
      if (country.toLowerCase().startsWith(inputValue.toLowerCase())) {
        let item = document.createElement("li");
        item.textContent = country;
        item.classList.add("autocomplete-item"); // Add the "autocomplete-item" class
        item.addEventListener("click", function() {
          input.value = country;
          autocompleteList.innerHTML = '';
        });
        item.addEventListener("mouseenter", function() {
          item.classList.add("active"); // Add the "active" class on hover
        });
        item.addEventListener("mouseleave", function() {
          item.classList.remove("active"); // Remove the "active" class when not hovering
        });
        autocompleteList.appendChild(item);
      }
    });
    showAutocompleteList(); // Display the list when input changes
  } else {
    hideAutocompleteList(); // Otherwise, hide the list
  }
});

// Event listener for "keydown" on the input field
input.addEventListener("keydown", function(e) {
  if (e.key === "Tab") {
    e.preventDefault(); // Prevent the default tab behavior

    // Handle the Tab key behavior for selecting an item
    var activeItem = autocompleteList.querySelector(".autocomplete-item.active");
    if (activeItem) {
      input.value = activeItem.textContent;
      autocompleteList.innerHTML = '';

      // Redirect to the corresponding HTML page
      var countryUrl = 'Countries/' + activeItem.textContent.toLowerCase().replace(/ /g, "-").toLowerCase() + '.html';
      window.location.href = countryUrl;
    }
  }

  // Only display the list if the input has at least one character
  if (input.value.length > 0) {
    showAutocompleteList();
  } else {
    hideAutocompleteList(); // Otherwise, hide the list
  }
});

// Event listener for clicking on the list items
autocompleteList.addEventListener("click", function(e) {
  if (e.target.classList.contains("autocomplete-item")) {
    // If the clicked element has the "autocomplete-item" class
    input.value = e.target.textContent;
    // Redirect to the corresponding HTML page
    var countryUrl = 'Countries/' + e.target.textContent.toLowerCase().replace(/ /g, "-").toLowerCase() + '.html';
    window.location.href = countryUrl;
    e.preventDefault(); // Prevent the default click behavior
  }
});

// Event listener to close the dropdown when clicking outside of the input field
document.addEventListener("click", function(e) {
  if (e.target !== autocompleteList && e.target !== input) {
    hideAutocompleteList();
  }
});

// Event listener for clicking inside the input field to display the dropdown
input.addEventListener("focus", function() {
  if (input.value.length > 0) {
    showAutocompleteList();
  }
});
<header>
  <h1>Select a country</h1>
</header>
<main>
  <div id="content-wrapper">
    <div id="get-container">
      <input type="text" id="country-name" placeholder="Enter a country" autocomplete="off">
      <div id="suggestion-list" class="autocomplete-items"></div>

      <div id="error-message"></div>
    </div>
    <div id="story-container">
      <div id="generated-text"></div>
      <button id="clear">Clear</button>
    </div>
  </div>
</main>

相关问题