首页 > 解决方案 > 将链接绑定到 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>

效果很好并根据给定的字符串生成选项。

在此处输入图像描述

除此之外,页面将链接绑定到返回的结果。

在此处输入图像描述

如何实现此功能?

标签: javascriptjquery

解决方案


您可以简单地使用autoComplete select功能,该功能可让您将链接绑定到返回的结果以进行自动完成。

您还需要像下面这样保存您的数据。因此,当点击选择时,可以打开自动完成单词的 URL。

要打开搜索结果,我们可以使用window.open这意味着 URL 将在新选项卡中打开。

工作演示: https ://jsfiddle.net/09dtrk7L/2/

运行下面的代码段(注意:这里不会打开网址,因此您需要尝试上面的演示链接。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>


推荐阅读