javascript - 将链接绑定到 jQuery 自动完成 UI 的返回结果
问题描述
此代码片段改编自jQuery 教程
<!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>
效果很好并根据给定的字符串生成选项。
除此之外,页面将链接绑定到返回的结果。
如何实现此功能?
解决方案
您可以简单地使用autoComplete
select
功能,该功能可让您将链接绑定到返回的结果以进行自动完成。
您还需要像下面这样保存您的数据。因此,当点击选择时,可以打开自动完成单词的 URL。
要打开搜索结果,我们可以使用window.open
这意味着 URL 将在新选项卡中打开。
运行下面的代码段(注意:这里不会打开网址,因此您需要尝试上面的演示链接。window.open
被代码段阻止。)
$(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>
推荐阅读
- java - 这个错误代码是什么意思?线程“主”java.util.InputMismatchException 中的异常
- javascript - Google Apps 脚本 - 电子邮件股票通知?
- qt - 如何在水平 QML 滚动视图上使用滚动
- javascript - 为什么我的正则表达式电子邮件验证不起作用?
- c# - 使用 Task.WhenAll 时如何获取结果
- spring - Spring kafka 多个消费者结果组合
- c# - c# linq join 具有不同名称的多个属性
- html - 带有 CSS 文件的 Django 模板不起作用
- python-3.x - 如何获取列中字母数字字符串的最大值?
- c# - 使用 gong 拖放在代码隐藏中创建 xaml 元素