我有一个无法解决的问题。我正在使用 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/