gpt4 book ai didi

typeahead.js - TypeaheadJS 方法不将数组转换为值

转载 作者:行者123 更新时间:2023-12-04 18:04:44 25 4
gpt4 key购买 nike

我正在使用 typeahead.js。

当我从 apiController 获取数据时,它看起来像这样:

["JobName1", "JobName1", "akhsfkh"]

当它通过这段代码时:

 $(function() {
var projectNumbers = $.getJSON("api/Project/GetAllNumbers")
.done(function(result) {
console.log(result);
return result; // ["JobName1", "JobName1", "akhsfkh"] is here
})
.fail(function(jqXHR, textStatus, err) {
alert('Error: ' + err);
});


var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;

// an array that will be populated with substring matches
matches = [];

// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');

// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});

cb(matches);
};
};

$('#jobNumber').typeahead({
hint: true,
minLength: 2,
highlight: true,
},
{

name: 'projects',
source: substringMatcher(projectNumbers.serializeArray()),
});
});

我的输入框显示前面的类型但可用数据是:

JobName1, JobName1, akhsfkh

substringMatcher 函数没有改变它。

有什么建议吗?

最佳答案

You cannot return results from a getJSON request like that

您必须存储结果并在回调中完成其余的工作。

var projectNumbers;
$.getJSON("http://jsbin.com/heyobi/1.json")
.done(function (result) {
projectNumbers = result;
initTypeahead();
})
.fail(function (jqXHR, textStatus, err) {
alert('Error: ' + err);
});

var substringMatcher = function (strs) {
......
});

function initTypeahead() {
$('.typeahead').typeahead({
hint: true,
minLength: 2,
highlight: true,
}, {
name: 'projects',
source: substringMatcher(projectNumbers),
});
}

这是一个DEMO

关于typeahead.js - TypeaheadJS 方法不将数组转换为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29145689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com