关于jQuery Autocomplete组件select(event, ui)事件及自动聚焦问题的咨询
Hey there, let's get that autocomplete search bar up and running with the resources you're using, including the auto-focus behavior for the results list. Here's a step-by-step breakdown:
1. Set Up Your Resources First
First, include the required jQuery and jQuery UI files in your HTML head. You already had these links, so I've formatted them cleanly here:
<!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- jQuery UI Theme --> <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/black-tie/jquery-ui.css"> <!-- jQuery UI Core --> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
2. Add the Search Input HTML
Next, drop a simple search input into your page. Giving it an ID makes it easy to target with jQuery:
<input type="text" id="search-input" placeholder="Type to search...">
3. Initialize the Autocomplete Plugin
Now let's write the jQuery code to power the autocomplete, including the auto-focus feature you mentioned. When the results dropdown pops up, it'll automatically focus on the first item in the list:
$(document).ready(function() { // Example static suggestions - replace this with your own data or an AJAX call const searchSuggestions = [ "Web Development", "jQuery Tips", "jQuery UI Autocomplete", "Frontend Best Practices", "Stack Overflow" ]; $("#search-input").autocomplete({ // Define where suggestions come from source: searchSuggestions, // Trigger when the dropdown opens open: function() { // Auto-focus the first result item $(".ui-autocomplete li:first-child").focus(); }, // Optional: Handle when a user selects a suggestion select: function(event, ui) { // Fill the input with the selected value $("#search-input").val(ui.item.value); // Add your own logic here (e.g., submit the search) return false; } }); });
Quick Notes on the Code:
source: This can be a static array like the example, or a function that fetches dynamic results via AJAX. For dynamic data, you'd replace the array with a function that makes a$.ajaxcall and returns the results.openEvent: This is where we handle the auto-focus. The.ui-autocompleteclass is a default class from jQuery UI, so targeting the first list item works reliably with your version of jQuery UI.selectEvent: Use this to customize what happens when a user picks a suggestion — like submitting a search form or navigating to a page.
Version Compatibility Check:
Since you're using jQuery 1.9.1 and jQuery UI 1.10.3, all the code above should work perfectly. The black-tie theme you included will style the autocomplete dropdown to match that theme, so if you see any styling oddities, just double-check that the CSS file loaded correctly.
内容的提问来源于stack exchange,提问作者Reginald1234

