为什么 Typeahead 在点击后在输入中显示 json 个对象

Why Typeahead shows json object in input after click

我的建议引擎工作正常,我只是有一个问题,因为当我点击项目时,它的 json 对象出现在输入元素中。我希望只有 OrgName 出现在输入值中。

<input class="form-control companySearch" type="text" value="" name="q" autocomplete="off" placeholder="Search a company">

var organization = new Bloodhound({
        remote: {
            url: '/search/org?term=%QUERY%',
            wildcard: '%QUERY%'
        },
        datumTokenizer: Bloodhound.tokenizers.whitespace('term'),
        queryTokenizer: Bloodhound.tokenizers.whitespace
    });
$(".companySearch").typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
    },
        {
            source: organization.ttAdapter(),       
            name: 'organizationsList',            
            templates: {                
                suggestion: function (data) {        
                    return '<a class="list-group-item ">' + data.OrgName + ', '+ data.address.Address+ ', '+ data.address.city.City+ ', ' + data.address.city.country.Country  + '</a>';                

                }
            }

        }
    );

我遇到了类似的问题并使用 typeahead 的 display 属性解决了它。

在你的例子中:

$(".companySearch").typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
    },
        {
            source: organization.ttAdapter(),       
            name: 'organizationsList',
            display: 'id', // PUT IT HERE
            templates: {                
                suggestion: function (data) {        
                    return '<a class="list-group-item ">' + data.OrgName + ', '+ data.address.Address+ ', '+ data.address.city.City+ ', ' + data.address.city.country.Country  + '</a>';                

                }
            }    
        }
    );

来自docs

display – For a given suggestion, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to stringifying the suggestion.

如果它不起作用,请尝试将 display 替换为 displayKey(我认为这是 typeahead 版本的内容)。