自动完成 jquery 搜索结果到定义的页面



我试图在使用自动完成jquery时获得一个静态的预定义搜索结果。

让我更具体地解释一下。

我正在编辑:http://jqueryui.com/autocomplete/#multiple,只是尝试了多个表单操作,但从未得到好的结果。

var availableTags = [
      "Apple",
      "Red",
      "iPhone"];

所以事情似乎很容易,但就我这个菜鸟而言,很难弄清楚。

当我在输入中输入"苹果"并单击Go按钮(通过表单操作或任何内容)时,我想转到"sitename.com/apple"地址。

当我同时输入"苹果,iPhone"并单击时,我想转到"sitename.com/apple+iphone"地址。

当我同时输入"red,iphone"并单击时,我想转到"sitename.com/red+iphone"地址。

我做了几次试验,但输入值让我像 ; sitename.com/q?=apple ,我找不到一种方法只显示/apple 而不显示"x?="。

我很高兴手动定义所有摊口,我正在为此寻求帮助。

谢谢!

我试过:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Multiple values</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
  <script>
  $(function() {
    var availableTags = [
      "Apple",
      "Red",
      "iphone"
    ];
    function split( val ) {
      return val.split( /,s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
 
    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            availableTags, extractLast( request.term ) ) );
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( "," );
          return false;
        }
      });
  });
  </script>
</head>
<body>
  <form method="get" action="http://example.com">
<div class="ui-widget">
  <input id="tags" name="asd" size="50">
</div>
  <input  type="submit" name="submit" value="Search"> 
 
 
</body>
</html> 

你可以这样做:

  1. 选择函数中使用+连接术语

this.urlValue = terms.join("+");

  1. 处理表单提交以重定向到正确的 URL

例如:

$('form').submit(function (e) {
    e.preventDefault();
    // Remove the last + from url value
    var urlValue = $('#tags')[0].urlValue.slice(0, -1);
    // Redirect to the url
    window.location.href = 'http://sitename.com/' + urlValue;
});

希望这有帮助。下面是一个演示来说明。

JSFiddle 演示

最新更新