Press "Enter" to skip to content

使用jQuery实现带有远程搜索和加载状态的多选示例。

<!DOCTYPE html>
<html>
<head>
  <title>多选示例</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
  <style>
    .selected {
      background-color: yellow;
    }
  </style>
</head>
<body class="container">
  <h2 class="mt-4">多选示例</h2>
  <div class="form-group mt-3">
    <input type="text" class="form-control" id="searchInput" placeholder="搜索...">
  </div>
  <div class="mt-3" id="loading" style="display: none;">加载中...</div>
  <ul class="list-group mt-3" id="results"></ul>
  <p class="mt-3">已选择:</p>
  <ul class="list-group" id="selectedItems"></ul>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    $(document).ready(function() {
      const searchInput = $('#searchInput');
      const loading = $('#loading');
      const results = $('#results');
      const selectedItems = $('#selectedItems');
      let selected = [];

      searchInput.on('input', function() {
        const searchTerm = $(this).val();
        // 显示加载状态
        loading.show();
        results.empty();

        // 模拟远程搜索,这里使用setTimeout来模拟延迟
        setTimeout(function() {
          // 模拟从服务器获取数据
          const data = getRemoteData(searchTerm);
          renderResults(data);
          loading.hide();
        }, 1000);
      });

      // 添加或移除已选择项
      results.on('click', 'li', function() {
        const item = $(this).text();
        if (selected.includes(item)) {
          selected = selected.filter(val => val !== item);
          $(this).removeClass('list-group-item-primary');
        } else {
          selected.push(item);
          $(this).addClass('list-group-item-primary');
        }
        updateSelectedItems();
      });

      function renderResults(data) {
        results.empty();
        data.forEach(function(item) {
          const listItem = $('<li class="list-group-item">').text(item);
          if (selected.includes(item)) {
            listItem.addClass('list-group-item-primary');
          }
          results.append(listItem);
        });
      }

      function updateSelectedItems() {
        selectedItems.empty();
        selected.forEach(function(item) {
          selectedItems.append($('<li class="list-group-item">').text(item));
        });
      }

      function getRemoteData(searchTerm) {
        // 模拟从服务器获取数据
        const data = [
          '选项1',
          '选项2',
          '选项3',
          '选项4',
          '选项5',
          '选项6',
        ];

        // 过滤匹配搜索条件的项
        return data.filter(item => item.toLowerCase().includes(searchTerm.toLowerCase()));
      }
    });
  </script>
</body>
</html>
发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注