jquery - 搜索框中的 Ajax/jQuery 自动完成 (Shopify)

标签 jquery ajax shopify

我希望在我的 Shopify 商店中的搜索栏上进行自动完成设置 - 这使用 Liquid 和 ajax

我找到了这个教程,并按照它的说明实现了它,但是它不起作用,网站上的任何搜索栏上都没有自动完成任何内容 - 我认为它可能很旧,并且是在更新/更改为“最小/”之前编写的Shopify 搜索功能。

https://help.shopify.com/themes/customization/store/enable-autocomplete-for-search-boxes

我可以使用 Chrome 开发工具来跟踪它,但它似乎卡在添加搜索结果列表 $('<ul class="search-results"></ul>').appendTo($(this)).hide(); 的位置。 ,在跟踪页面的 HTML 时不会出现此情况。这意味着当它稍后尝试查找此列表 var resultsList = form.find('.search-results'); 时它找不到它,因此无法填充项目。

我正在运行最小主题。 网站是testing site搜索栏位于顶部灰色标题,也位于/search

Shopify 构建的用于演示此自动完成功能的测试站点位于 [https]://search-autocomplete.myshopify.com/。 <ul>页面加载时附加已经存在。

编辑:

做了更多的挖掘,我在开发工具中偶然发现了这个错误 -

Uncaught ReferenceError: jQuery is not defined at (index):7031

您猜对了,这就是下面 jQuery 代码的第一行。 $(function() {知道为什么 jQuery 未定义吗?该脚本包含在我的索引文件底部 </body> 之前,所以 jquery.min.js 应该已经加载,网站上的其余 jQuery 工作正常。

测试站点上的表单代码

<form action="/search" method="get" class="site-header__search small--hide" role="search">
        {% comment %}<input type="hidden" name="type" value="product">{% endcomment %}
        <div class="site-header__search-inner">
          <label for="SiteNavSearch" class="visually-hidden">{{ 'general.search.placeholder' | t }}</label>
          <input type="search" name="q" id="SiteNavSearch" placeholder="{{ 'general.search.placeholder' | t }}" aria-label="{{ 'general.search.placeholder' | t }}" class="site-header__search-input">
        </div>

        <button type="submit" class="text-link site-header__link site-header__search-submit">
          {% include 'icon-search' %}
          <span class="icon__fallback-text">{{ 'general.search.submit' | t }}</span>
        </button>
      </form>

搜索.json

{% layout none %}
{% capture results %}
  {% for item in search.results %}
{% assign product = item %}
{ 
  "title"    : {{ product.title | json }},
  "url"      : {{ product.url | within: product.collections.last | json }},
  "thumbnail": {{ product.featured_image.src | product_img_url: 'thumb' | json }}
}
{% unless forloop.last %},{% endunless %}
 {% endfor %}
{% endcapture %}
{
"results_count": {{ search.results_count }},
"results": [{{ results }}]
}

搜索自动完成.liquid

<script>
$(function() {
  // Current Ajax request.
  var currentAjaxRequest = null;

  // Grabbing all search forms on the page, and adding a .search-results list to each.
   var searchForms = 
 $('form[action="/search"]').css('position','relative').each(function() {

 // Grabbing text input.
   var input = $(this).find('input[name="q"]');

  // Adding a list for showing search results.
    var offSet = input.position().top + input.innerHeight();
    $('<ul class="search-results"></ul>').css( { 'position': 'absolute', 'left': '0px', 'top': offSet } ).appendTo($(this)).hide();    

 // Listening to keyup and change on the text field within these search forms.
   input.attr('autocomplete', 'off').bind('keyup change', function() {

// What's the search term?
  var term = $(this).val();

 // What's the search form?
  var form = $(this).closest('form');

 // What's the search URL?
  var searchURL = '/search?type=product&q=' + term;

 // What's the search results list?
  var resultsList = form.find('.search-results');

  // If that's a new term and it contains at least 3 characters.
  if (term.length > 3 && term != $(this).attr('data-old-term')) {

   // Saving old query.
    $(this).attr('data-old-term', term);

  // Killing any Ajax request that's currently being processed.
    if (currentAjaxRequest != null) currentAjaxRequest.abort();

  // Pulling results.
    currentAjaxRequest = $.getJSON(searchURL + '&view=json', function(data) {
      // Reset results.
      resultsList.empty();

    // If we have no results.
      if(data.results_count == 0) {

     // resultsList.html('<li><span class="title">No results.</span></li>');
        // resultsList.fadeIn(200);
        resultsList.hide();
      } else {

       // If we have results.
        $.each(data.results, function(index, item) {
          var link = $('<a></a>').attr('href', item.url);
          link.append('<span class="thumbnail"><img src="' + item.thumbnail + '" /></span>');
          link.append('<span class="title">' + item.title + '</span>');
          link.wrap('<li></li>');
          resultsList.append(link.parent());
        });

       // The Ajax request will return at the most 10 results.
        // If there are more than 10, let's link to the search results page.
        if(data.results_count > 10) {
          resultsList.append('<li><span class="title"><a href="' + searchURL + '">See all results (' + data.results_count + ')</a></span></li>');
        }
        resultsList.fadeIn(200);
      }        
    });
  }
});
 });

 // Clicking outside makes the results disappear.
 $('body').bind('click', function(){
  $('.search-results').hide();
 });
 });
</script>

最佳答案

这里是为了后代和完整性。

经过一些调整,我终于让它工作了。

为了修复 jQuery 未定义错误,我将第一行替换为: window.onload = (function() {

由于某种原因,结果列表从某处获取了一个 display:block,但我找不到它,所以使用 jQuery 我将其更改为 block,使其出现。另外,在此代码行中,我修改了 term.length在 2 上启动 ajax 请求,否则如果您输入 cat/dog,则需要输入另一个字母或空格来开始搜索。

// If that's a new term and it contains at least 2 characters. if (term.length > 2 && term != $(this).attr('data-old-term')) { $('<ul class="search-results"></ul>').css( { 'display': 'block'} )

搜索结果现已显示,并且全部正确!只需要进行一些 CSS 调整即可定位。

关于jquery - 搜索框中的 Ajax/jQuery 自动完成 (Shopify),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45477730/

相关文章:

ios - 如何将自定义类转换为 objective-c 中的 json 数组或 json 字典?

node.js - 在 Shopify 商店的 shop.json 中编辑 force_ssl 选项

ruby - Shopify脚本编辑器使用产品标签而不是id

jQuery ui 1.7.3 datepicker 设置选定日期+ 3 天

javascript - 我想要一个垂直(反馈)按钮在鼠标悬停时有一个轻微的动画滑出效果

javascript - 更新 .php 页面的部分内容

jquery - 如何在文档加载时立即进行 AJAX 调用

javascript - 动态更改 Twitter Bootstrap 3 中的图标

javascript - FullCalendar 插件 3.1.0 显示不正确

php - 通过 AJAX 获取用户特定数据