【问题标题】:TypeaheadJS Method not converting Array to valuesTypeaheadJS 方法未将数组转换为值
【发布时间】:2015-05-22 15:10:22
【问题描述】:

我正在使用 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 函数没有改变它。

有什么建议吗?

【问题讨论】:

    标签: typeahead.js


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      相关资源
      最近更新 更多