You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery autocomplete函数中访问$(this)?多元素动态调用实现

Reusable jQuery Autocomplete for Multiple Inputs

Great question! Instead of duplicating code for each search box, you can create a single, reusable initialization that dynamically pulls each input's unique settings from its data attributes. Here's how to do it cleanly:

Step 1: Update Your HTML (add custom data attributes as needed)

First, ensure all your search inputs share the autocomplete-search class and include their specific data-search-url (and any other custom settings you want to define per input):

<input type="text" name="brand" id="brand" class="autocomplete-search" data-search-url="/api/v1/search/brands" data-min-length="2">
<input type="text" name="product" id="product" class="autocomplete-search" data-search-url="/api/v1/search/products" data-min-length="1">
<input type="text" name="category" id="category" class="autocomplete-search" data-search-url="/api/v1/search/categories">

Step 2: Write the Reusable jQuery Code

This code will loop through every matching input, pull its unique settings, and initialize the autocomplete component with those values:

$(document).ready(function() {
  // Iterate over each autocomplete-enabled input
  $('.autocomplete-search').each(function() {
    const $input = $(this);
    
    // Extract dynamic settings from data attributes
    const searchEndpoint = $input.data('search-url');
    // Use a default value if the data attribute isn't present on an input
    const minSearchLength = $input.data('min-length') || 1;

    // Initialize Autocomplete with element-specific configuration
    $input.autocomplete({
      source: function(request, response) {
        // Send AJAX request to the input's unique API endpoint
        $.ajax({
          url: searchEndpoint,
          method: 'GET',
          data: {
            term: request.term // Pass the user's input to the API
          },
          success: function(apiData) {
            // Forward the API's results to the autocomplete component
            response(apiData);
          },
          error: function() {
            // Fallback to empty results if the API call fails
            response([]);
          }
        });
      },
      minLength: minSearchLength,
      select: function(event, ui) {
        // Optional: Custom behavior when an item is selected
        console.log(`Selected ${ui.item.label} for ${$input.attr('name')}`);
        // You could also populate hidden fields or trigger other actions here using data attributes
      },
      focus: function(event, ui) {
        // Optional: Keep the input showing the label instead of value when focusing an item
        event.preventDefault();
        $input.val(ui.item.label);
      }
    });
  });
});

Key Benefits of This Approach:

  • No duplicated code: You only write the autocomplete logic once, even if you have 10+ search boxes.
  • Flexibility: Add more data attributes (like data-delay or data-max-results) and pull them into the config without rewriting core logic.
  • Maintainability: If you need to update how the autocomplete works, you only change one block of code instead of multiple instances.

Notes to Keep in Mind:

  • Make sure your API endpoints accept a term parameter (adjust the data object in the AJAX call if your API uses a different name, like q).
  • The API should return data in a format jQuery Autocomplete understands: either an array of strings (e.g., ["Nike", "Adidas"]) or an array of objects with label and value properties (e.g., [{label: "Nike", value: 1}, ...]).
  • For advanced per-input customizations, you could even add data attributes like data-select-handler and map them to specific functions, but that's an optional tweak.

内容的提问来源于stack exchange,提问作者Tony Beninate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:21:58