使用 bloodhound 将 DOM 元素的值传递给 typeahead

Pass value from DOM element into typeahead with bloodhound

我想将隐藏输入字段的值传递给 bloodhound 中的搜索远程 URL 参数。

该变量是动态的,每次打开模式弹出窗口时都会更新。它的初始值为空,我相信这就是它根本不起作用的原因:

url: url + 'equipment/getSuggestions/' + $('#equipment-type-input').val() + '/%QUERY',

如您所见,我使用 jQuery 获取它,但值为空。可能是因为它只在插件初始化时获取一次?

这里是完整的脚本:

// Instantiate the Bloodhound suggestion engine
var suggestions = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: url + 'equipment/getSuggestions/' + $('#equipment-type-input').val() + '/%QUERY',
        wildcard: '%QUERY',
        filter: function (movies) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(movies, function (movie) {
                return {
                    value: movie
                };
            });
        }
    }
});

// Initialize the Bloodhound suggestion engine
suggestions.initialize();

// Instantiate the Typeahead UI
$('#equipment-id-input').typeahead(null, {
    displayKey: 'value',
    source: suggestions.ttAdapter()
});

您可以将 Bloodhound 的 遥控器 设置为如下所示:

remote: {
  url: '/equipment/getSuggestions/%EQUIPMENT/%QUERY',
  replace: function(url) {
    return url.replace('%EQUIPMENT', $('#equipment-type-input').val()).replace('%QUERY', $('input.typeahead.tt-input').val());
  },
  filter: function (movies) {
    // Map the remote source JSON array to a JavaScript object array
    return $.map(movies, function (movie) {
      return {
        value: movie
      };
    });
  }
}

您不再需要 通配符,因为您必须替换 replace 参数中的 %QUERY。

我最后是这样解决的:

// Instantiate the Bloodhound suggestion engine
var suggestions = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: url + 'equipment/getSuggestions/',
        replace: function (url, query) {
            return url + query.toUpperCase() + '/' + $('#equipment-type-input').val()
        },
        wildcard: '%QUERY',
        filter: function (numbers) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(numbers, function (number) {
                return {
                    value: number
                };
            });
        }
    }
});

// Initialize the Bloodhound suggestion engine
suggestions.initialize();

// Instantiate the Typeahead UI
$('#equipment-id-input').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
}, {
    limit: 7,
    displayKey: 'value',
    source: suggestions.ttAdapter(),
});