jQuery自动完成>选择>链接

时间:2012-06-25 23:24:54

标签: javascript jquery jquery-ui jquery-ui-autocomplete

我实现了这个代码,我喜欢它是多么直接,因为我计划将ALOT添加到Source中 - 但是对于我的生活,我无法弄清楚如何将所选的一个添加为链接。

EG>开始打字>自动填充工作>选择>转到该URL

当前代码:

<!DOCTYPE html>
<html>
<head>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function() {
    $("input#autocomplete").autocomplete({
    source: ["NYC", "LA", "Philly", "Chitown", "DC", "SF", "Peru"]
});
  });
  </script>
</head>
<body style="font-size:62.5%;">

<input id="autocomplete" />

</body>
</html>

我在这里找到了一些关于此的讨论,但没有一个代码建议有效。如何添加与上述值相关联的URL;如果我可以保持相同的语法并且接近值添加,我会很高兴; EG:“秘鲁”www.peru.com

1 个答案:

答案 0 :(得分:14)

您可以向源数组中的每个对象添加url属性,然后在用户选择项目时将window.location设置为该URL:

$(document).ready(function() {
    $("input#autocomplete").autocomplete({
        source: [
             { value: "NYC", url: 'http://www.nyc.com' }, 
             { value: "LA", url: 'http://www.la.com' },
             { value: "Philly", url: 'http://www.philly.com' },
             { value: "Chitown", url: 'http://www.chitown.com' },
             { value: "DC", url: 'http://www.washingtondc.com' },
             { value: "SF", url: 'http://www.sanfran.com' },
             { value: "Peru", url: 'http://www.peru.com' }
        ],
        select: function (event, ui) {
            window.location = ui.item.url;
        }
    });
});