【问题标题】:how to do autocomplete search working with input?如何使用输入进行自动完成搜索?
【发布时间】:2018-07-14 18:05:24
【问题描述】:

我需要 jquery 或 javascript 来执行自动完成下拉列表,其中包含我的搜索输入结果。我需要将结果作为链接“”,以便我可以在新选项卡中打开它或通过单击它直接打开它。 这是我的代码:

<input type="text" id="searchinput" class="search-input" placeholder="Search here.." />

<ul id="main-menu">   
    <li class="has-sub"><a href="javascript:;"><span class="title">Menu Header1</span></a>
       <ul>
          <li><a href="example.com"><span class="childtitle">brand one</span></a></li>
          <li><a href="example.com"><span class="childtitle">brand two</span></a></li>
       </ul>    
    </li>

    <li class="has-sub"><a href="javascript:;"><span class="title">Menu Header2</span></a>
       <ul>
          <li><a href="example.com"><span class="childtitle">Car BMW</span></a></li>
          <li><a href="example.com"><span class="childtitle">Car Toyota</span></a></li>
          <li><a href="example.com"><span class="childtitle">Car Opel</span></a></li>
          <li><a href="example.com"><span class="childtitle">Car Kia</span></a></li>
       </ul>
    </li>
</ul>

【问题讨论】:

  • 是的,您可以使用 jQuery UI 自动完成功能来做到这一点。在此处查看演示...并根据您的代码要求进行更改。[jqueryui.com/autocomplete/#categories].希望对您有所帮助。
  • thnx Bharat 重播 .. 但由于我是初学者,所以我不明白我必须做什么:(
  • 抱歉重播晚了。您只需包含 jQueryUi 插件并根据需要更新此演示。
  • @BharatMakvana 谢谢你,我找到了答案并添加到这里

标签: javascript jquery search input


【解决方案1】:

纯 JavaScript 的可能解决方案。

  • 再次创建与输入匹配的标签数组
  • 为输入字段设置input事件监听器
  • 在每个input事件上,清除列表元素的内容并基于一些匹配函数,动态创建一个新的,添加 每个匹配字符串的链接

// array of values to match against
const tags = ['bmw', 'toyota', 'opel', 'kia'];

// fetch input and list elements
const input = document.querySelector('input');
const list = document.querySelector('ul');

// simple match function, performs substing matching
const getMatch = (toMatch, tags) =>
  tags.filter((tag) => tag.includes(toMatch.toLowerCase()));

input.addEventListener('input', (event) => {
  // clear contents of list
  list.innerHTML = '';

  // start matching only when input field is non-empty
  if (input.value !== '') {
    // call matching function and create a link for each
    // item returned by it
    getMatch(input.value, tags).forEach((match) => {
      const item = document.createElement('li');
      list.append(item);

      const link = document.createElement('a');
      item.append(link);

      // add href attribute and text dynamically
      link.setAttribute('href', `www.example.com/${match}`);
      link.textContent = match;
    });
  }
});
Search: <input type="text">
<ul></ul>

【讨论】:

  • 非常感谢@Matus,但我在这段代码中缺少三件事..首先我需要结果在输入下显示为下拉列表,并带有我写的字母标记..其次我需要结果得到它自己的href链接,因为它在&lt;a&gt;元素中,如example1.com和example2.com等。最后可以用class="childtitle"来定位结果
  • @MuhammadS.Eltyar result to appear like dropdown list under the input,无需更改此代码,只需使用 css 设置 ulli 元素的样式即可。 result to get it's own href link 他们确实有自己的链接,但是如果您需要确切的格式,请将 .forEach((match) 更改为 .forEach((match, idx)www.example.com/${match} 更改为 www.example${idx+1}.com 并为这些新创建的链接添加一个类,添加 link.className = 'childtitle'; 行到forEach 块的底部。
  • 非常感谢..但你没有得到我需要的东西..首先..我不需要向新创建的链接添加类,但我需要获取所有带有类@的项目987654337@ 在我上面的 html 代码中,而不是您在代码 const tags = ['bmw', 'toyota', 'opel', 'kia']; 中提到的静态数组,因为我需要它从 ul 菜单中动态获取页面名称。第二..需要到达那里href属性例如“品牌一”页面有网址href="example.com"和“品牌二”页面有网址href="google.com"等..提前感谢您的帮助@Matus
【解决方案2】:

我在这里找到了@MatusDubrava 脚本和其他一些帮助的解决方案..

$(function () {
                            var menuPages = $('#main-menu li a:has(.childtitle)').map(function () {
                                return {
                                    label: $(this).text(),
                                    value: $(this).attr('href')
                                };
                            }).toArray();
                            $("#txt_MenuSearch").autocomplete({
                                source: menuPages,
                                select: function (event, target) {
                                    /* On select, show item's label in text input */
                                    event.preventDefault();
                                    $("#txt_MenuSearch").val(target.item.label);
                                    var link = target.item.value;
                                    window.open(link);
                                },
                            });
                            /* Highlight text */
                            $("#txt_MenuSearch").data("ui-autocomplete")._renderItem = function (ul, item) {
                                var newText = String(item.label).replace(
                                    new RegExp(this.term, "gi"),
                                    "<span style='color:#DDBA15'>$&</span>");

                                /* Wrapping the matching option within <a> tags */
                                newText = '<a href="' + item.value + '">' + newText + '</a>';

                                return $("<li>")
                                .attr("data-value", item.value)
                                .append(newText)
                                .appendTo(ul);
                            };
                        });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/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>

<input type="text" id="txt_MenuSearch" class="search-input" placeholder="Search here.." />

<ul id="main-menu">   
    <li class="has-sub"><a href="javascript:;"><span class="title">Menu Header1</span></a>
       <ul>
          <li><a href="example.com"><span class="childtitle">brand one</span></a></li>
          <li><a href="example.com"><span class="childtitle">brand two</span></a></li>
       </ul>    
    </li>

    <li class="has-sub"><a href="javascript:;"><span class="title">Menu Header2</span></a>
       <ul>
          <li><a href="example.com"><span class="childtitle">Car BMW</span></a></li>
          <li><a href="example.com"><span class="childtitle">Car Toyota</span></a></li>
          <li><a href="example.com"><span class="childtitle">Car Opel</span></a></li>
          <li><a href="example.com"><span class="childtitle">Car Kia</span></a></li>
       </ul>
    </li>
</ul>

【讨论】:

    猜你喜欢
    • 2012-01-14
    • 2019-06-28
    • 1970-01-01
    • 2015-04-10
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2017-09-22
    相关资源
    最近更新 更多