javascript - jquery typeahead 设置静态第一个元素,然后按 asc 排序其他元素

标签 javascript jquery

我有一个无法解决的问题。我正在使用 runningcoder ( http://www.runningcoder.org/jquerytypeahead/ ) 中的 jquery typeahead,并且我尝试设置一个静态第一个元素,该元素始终是第一个元素,然后是按 asc 顺序排列的其他元素。

我的代码如下:

$.typeahead({
        input: ".js-typeahead",
        minLength: 0,
        maxItem: false,
        order: "asc",
        emptyTemplate: '<span class="text-muted">Nessun paese corrisponde a <strong>{{query}}</strong></span>',
        searchOnFocus: true,
        source: {
            groupName: {
                // Ajax Request
                ajax: {
                    url: "../wp-json/shipping-data/available-countries",
                    callback: {
                        done: function (data) {
                            $.each(data, function (index, value) {
                                data[index] = SUtils.lowerCaseAllWordsExceptFirstLetters(value);
                            });
                            return data;
                        }
                    }
                }
            }
        },
        debug: true
    });

我试图将意大利国家作为列表中建议的第一个元素,但我无法实现这一点,因为指令“order:asc”正在重新排序数据数组。我如何拥有“order: asc”但将意大利作为列表中的第一个元素?

谢谢

最佳答案

由于我没有您的完整实现,这是我从您的代码片段中猜测的。基本上,您必须找到该元素(在本例中为“Italy”),然后将其放入数组的第一个元素,并用其他项目填充数组。像这样的事情:

done: function (data) {
  const sortedData = $.each(data, function (index, value) {
    data[index] = SUtils.lowerCaseAllWordsExceptFirstLetters(value);
  });
  sortedData = [
    sortedData.find(item => item == 'Italy'), //find item which is 'Italy'
    ...sortedData.filter(item => item != 'Italy') //spread operation to fill the array with the rest of the items which are not `Italy`
  ];
  return sortedData;
}

关于javascript - jquery typeahead 设置静态第一个元素,然后按 asc 排序其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861186/

相关文章:

javascript - 隐藏的div没有正确加载javascript

javascript - ajax 内容上的 jQuery 脚本不使用 $(document).on

javascript - slider Jquery mobile 中缺少句柄 View

jquery - 站点计数器图像 - 如何将数字放入其中

javascript - 一旦 div 高度达到最大高度,动态扩展 div 的宽度到内容

javascript - native JS 二进制渲染

javascript - 最后使用 jQuery 获取并追加元素

javascript - 在深度模块化的 Backbone、Require.js 和 D3 应用程序中,如何确保一个函数在另一个函数之前被调用?

javascript - 使用 for 循环和列表将 props 传递给 RN 组件

javascript - 像 Google 日历中一样的表单对话框