问题
This code snippet is adapted from a jQuery tutorial
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"];
$("#tags").autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags"> </div>
</body>
</html>
Which works well and generates options according to a given string.
Beside that, a page binds links to the returned results.
How do I implement this feature?
回答1:
You can simply use autoComplete
select
feature which will let you binds links to the returned results for autocomplete.
You also need to save your data like this below. So the URL of autocomplete words can be opened when clicked on the selection.
To open the search results we can use window.open
this mean the url will be opened in new tab.
Working Demo: https://jsfiddle.net/09dtrk7L/2/
Run snippet below (Note: The url will not open here so you need to try the Demo link above. window.open
is blocked by the snippet.)
$(function() {
//Your autocomplete data
var availableTags = [{
value: "Google",
url: "http://www.google.com/",
label: "Google"
},
{
value: "Example website",
url: "http://www.google.com/",
label: "Example website"
},
];
//Autocomplete
$("#tags").autocomplete({
source: availableTags,
//Open window on select
select: function(event, data) {
window.open(data.item.url, '_blank');
}
});
});
.ui-menu-item-wrapper {
text-decoration: underline;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags"> </div>
</body>
</html>
来源:https://stackoverflow.com/questions/63089431/binds-links-to-the-returned-results-for-jquery-autocomplete-ui