使用 Bootstrap3-typeahead 将对象传递给 onSelect

Passing an object to onSelect using Bootstrap3-typeahead

BootStrap3-TypeAhead

大家好,我无法弄清楚我应该如何将除默认值之外的任何对象传递给 onSelect 以获得更广泛的用途。这是我的代码,如有任何帮助,我们将不胜感激!

$("input[type='text']").typeahead({
    onSelect: function(item) {
        // Do things with the item object here.
    },
    items: 10,
    ajax: {
        url: "modules/scripts/Search.php",
        timeout: 500,
        triggerLength: 1,
        method: "POST",
        preDispatch: function (str) {
            return {
                String: str,
                State: $("#"+$("#"+InputBox).attr("data-place")+"StateText").attr("data-sc")
            }
        },
        preProcess: function (data) {
            if (data.success === false) { return false; }
            // I think I'd create the item object here, or pass it along?

            var DD = [];
            $.each(data, function(key, value) {
                DD.push(value['City']+" - "+value['Zip']);
                TempArr[value['ID']] = data[key];
            });

            return DD;
        }
    }
});

您似乎在使用 jQuery-UI 自动完成语法。 Typeahed 使用 Bloodhound 建议引擎。检查 Typeahead documentation。 听到 Typeahead 自定义事件:typeaead:selected 让您检索 jQuery 事件对象、建议对象和建议所属的数据集的名称。

我最终使用 .remote.filter: function(obj) {} 选项解决了这个问题。这是一个片段:

var AjaxOptions = {
    type: "POST",
    cache: false,
    data: { limit: 10 },
    beforeSend: function(jqXHR, settings){
        // Manipulate settings.data to send more information than just the query string.
    },
    complete: function(data) {
        // If desired, you could do a 'how long this query took' display here.
    }
}

var InputArea = new Bloodhound({
    datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.val); },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    remote: {
        cache: false,
        url: 'scripts/Query.php?q=%QUERY',
        filter: function (InputArea) {
            return $.map(InputArea, function (data) {
                // Do whatever you want with 'data', then return it

                return {
                    foo: bar,
                    arnold: data.palmer
                };
            });
        },
        ajax: AjaxOptions,
    }
});