📜  HTML | DOM onsearch 事件(1)

📅  最后修改于: 2023-12-03 15:15:35.469000             🧑  作者: Mango

HTML | DOM onsearch 事件

The onsearch event is triggered when the user interacts with the search input field in HTML. It is a DOM event that allows us to handle or perform some actions when the search input field value changes.

Syntax

The onsearch event is written as an attribute, and it is prefixed with on. Here is how it is declared:

<input onsearch="myFunction()">
How it works

The onsearch event is triggered whenever the user types something into a search field or clears the field by pressing the X button or the Escape key.

We can use the onsearch event to perform some actions whenever the search field is interacted with. For example, we can perform a search or filter items on a list based on the input value, display search suggestions, or highlight matching words in the search results.

Here is a simple example that demonstrates how the onsearch event works:

<!DOCTYPE html>
<html>
<body>

  <input type="search" onsearch="searchFunction()" placeholder="Search...">

  <ul id="myList">
    <li>Apple</li>
    <li>Banana</li>
    <li>Cherry</li>
    <li>Durian</li>
    <li>Eggplant</li>
  </ul>

  <script>
    function searchFunction() {
      let input = document.querySelector("input[type='search']");
      let filter = input.value.toUpperCase();
      let ul = document.querySelector("#myList");
      let li = ul.getElementsByTagName("li");
      for (let i = 0; i < li.length; i++) {
        let a = li[i];
        if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
          li[i].style.display = "";
        } else {
          li[i].style.display = "none";
        }
      }
    }
  </script>

</body>
</html>

In this example, whenever the user types something into the search field, the searchFunction() is called, which filters the items in the list based on the input value. The searchFunction() compares the searched text with the contents of the list items, then hides or displays the ones that match or don't.

Note: The `onsearch` event is not supported by some older browsers, such as Internet Explorer 8 and earlier versions.
Conclusion

The onsearch event is a useful DOM event that allows us to handle search field interactions in HTML. We can use the onsearch event to perform different search-related tasks, such as filtering lists, displaying search suggestions, or highlighting matching words in search results.