首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

与JQUERY中的自动完成类似的自定义组件

在Web开发中,类似于jQuery中的自动完成功能,可以使用多种现代前端技术和框架来实现自定义组件。以下是一些流行的方法和示例:

1. 使用原生JavaScript和CSS

你可以使用原生JavaScript和CSS来创建一个简单的自动完成组件。

HTML

代码语言:javascript
复制
<input type="text" id="autocomplete" placeholder="Type to search...">
<div id="suggestions"></div>

CSS

代码语言:javascript
复制
#suggestions {
  border: 1px solid #ccc;
  max-height: 150px;
  overflow-y: auto;
  display: none;
}

.suggestion-item {
  padding: 8px;
  cursor: pointer;
}

.suggestion-item:hover {
  background-color: #f0f0f0;
}

JavaScript

代码语言:javascript
复制
const data = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

document.getElementById('autocomplete').addEventListener('input', function(e) {
  const input = e.target.value.toLowerCase();
  const suggestionsContainer = document.getElementById('suggestions');
  suggestionsContainer.innerHTML = '';

  if (input.length > 0) {
    const filteredData = data.filter(item => item.toLowerCase().includes(input));
    filteredData.forEach(item => {
      const div = document.createElement('div');
      div.className = 'suggestion-item';
      div.textContent = item;
      div.addEventListener('click', function() {
        document.getElementById('autocomplete').value = item;
        suggestionsContainer.style.display = 'none';
      });
      suggestionsContainer.appendChild(div);
    });
    suggestionsContainer.style.display = 'block';
  } else {
    suggestionsContainer.style.display = 'none';
  }
});

2. 使用React

如果你使用React,可以创建一个更复杂和可复用的自动完成组件。

安装依赖

代码语言:javascript
复制
npm install axios

组件代码

代码语言:javascript
复制
import React, { useState } from 'react';
import axios from 'axios';

const Autocomplete = ({ endpoint }) => {
  const [inputValue, setInputValue] = useState('');
  const [suggestions, setSuggestions] = useState([]);

  const handleInputChange = async (e) => {
    const value = e.target.value;
    setInputValue(value);

    if (value.length > 0) {
      try {
        const response = await axios.get(`${endpoint}?query=${value}`);
        setSuggestions(response.data);
      } catch (error) {
        console.error('Error fetching suggestions:', error);
      }
    } else {
      setSuggestions([]);
    }
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        placeholder="Type to search..."
      />
      <ul>
        {suggestions.map((suggestion, index) => (
          <li key={index} onClick={() => setInputValue(suggestion)}>
            {suggestion}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Autocomplete;

使用组件

代码语言:javascript
复制
import React from 'react';
import ReactDOM from 'react-dom';
import Autocomplete from './Autocomplete';

const App = () => {
  return (
    <div>
      <h1>Autocomplete Example</h1>
      <Autocomplete endpoint="/api/suggestions" />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

3. 使用Vue.js

如果你使用Vue.js,也可以创建一个类似的自动完成组件。

组件代码

代码语言:javascript
复制
<template>
  <div>
    <input
      type="text"
      v-model="inputValue"
      @input="fetchSuggestions"
      placeholder="Type to search..."
    />
    <ul v-if="suggestions.length">
      <li v-for="(suggestion, index) in suggestions" :key="index" @click="selectSuggestion(suggestion)">
        {{ suggestion }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      suggestions: []
    };
  },
  methods: {
    async fetchSuggestions() {
      if (this.inputValue.length > 0) {
        try {
          const response = await fetch(`/api/suggestions?query=${this.inputValue}`);
          const data = await response.json();
          this.suggestions = data;
        } catch (error) {
          console.error('Error fetching suggestions:', error);
        }
      } else {
        this.suggestions = [];
      }
    },
    selectSuggestion(suggestion) {
      this.inputValue = suggestion;
      this.suggestions = [];
    }
  }
};
</script>

<style>
ul {
  list-style-type: none;
  padding: 0;
  border: 1px solid #ccc;
  max-height: 150px;
  overflow-y: auto;
}

li {
  padding: 8px;
  cursor: pointer;
}

li:hover {
  background-color: #f0f0f0;
}
</style>

使用组件

代码语言:javascript
复制
<template>
  <div>
    <h1>Autocomplete Example</h1>
    <autocomplete />
  </div>
</template>

<script>
import Autocomplete from './Autocomplete.vue';

export default {
  components: {
    Autocomplete
  }
};
</script>

这些示例展示了如何使用原生JavaScript、React和Vue.js来创建类似于jQuery自动完成的组件。你可以根据自己的需求和技术栈选择合适的方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

10分46秒

024_尚硅谷react教程_类式组件中的构造器与props

7分32秒

React基础 组件核心属性之props 5 类式组件中的构造器与props 学习猿地

48秒

工程监测多通道振弦温度模拟信号采集仪VTN结构与特点

39秒

高性价比多通道振弦传感器无线采集采发仪VS10x结构与特点

5分33秒

JSP 在线学习系统myeclipse开发mysql数据库web结构java编程

领券