从Typeahead传递参数到Bloodhound?

7

我正在使用Typeahead设置一个表单。我有两个并排的输入框,我需要为它们每个都提供自动完成功能。我的HTML代码如下:

<select id="numerator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="numeratorId" class="typeahead" type="text" />
<br/>
<select id="denominator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="denominatorId" class="typeahead" type="text" />

每个输入字段都将通过查看API端点来自动完成。这应该是形式为/api/1.0/code?type=presentation&code=123/api/1.0/code?type=chemical&code=123
API调用中的type参数的值应取决于紧挨每个输入字段的<select>元素的值。
我遇到的问题是我不知道如何告诉Bloodhoundtype参数应该是什么。
理想情况下,我想将其传递给Bloodhound,但我不知道如何做到这一点。 这是我的JavaScript代码:
var bnfMatches = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
      url: '/api/1.0/code?',
      replace: function(url, uriEncodedQuery) {
        url = url + 'code=' + uriEncodedQuery;
        // How to change this to denominator for denominator queries?
        val = $('#numerator').val(); 
        if (!val) return url;
        return url + '&code_type=' + encodeURIComponent(val)
      }
  }
});

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
},
{
    name: 'states',
    displayKey: 'id',
    source: bnfMatches.ttAdapter()
});

如果有任何建议,我将不胜感激。


两个 input 元素的 id 都是相同的吗?是 numeratorId 吗? - guest271314
抱歉,那是一个错误。已经修复。 - Richard
иҮ·жџӨзњ‹её–е­ђгЂ‚и°ѓж•өдғ†inputе…ѓзө зљ„idпәЊж·»еЉ дғ†bnfMatches.initialize()пәЊйЂ‰ж‹©е…·жњ‰д»Ө聚焦的inputе…ѓзө idеәЂе¤өзљ„selectе…ѓзө гЂ‚ - guest271314
2个回答

5

尝试

HTML

注意,在input元素中删除了重复的id numeratorId;分别替换为numeratorIddenominatorId。这也允许在replace函数中选择select元素。

<select id="numerator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="numeratorId" class="typeahead" type="text" />
<br/>
<select id="denominator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="denominatorId" class="typeahead" type="text" />

JavaScript

注意,bnfMatches没有初始化。在设置Bloodhound后添加 bnfMatches.initialize();

var bnfMatches = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: {
          url: '/api/1.0/code?',
          replace: function(url, uriEncodedQuery) {
            var val = $(".typeahead").filter(":focus")
                     .attr("id").slice(0, -2);
            var res = (url + "type=" + $("#" + val).val() + "&code=" 
                      + encodeURIComponent(uriEncodedQuery));
            console.log(res);
            return res
          }
      }
    });

    bnfMatches.initialize();

    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 2
    },
    {
        name: 'states',
        displayKey: 'id',
        source: bnfMatches.ttAdapter()
    });

var bnfMatches = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
      url: '/api/1.0/code?',
      replace: function(url, uriEncodedQuery) {
        var val = $(".typeahead").filter(":focus")
                 .attr("id").slice(0, -2);
        var res = (url 
                  + "type=" + $("#" + val).val() + "&code=" 
                  + encodeURIComponent(uriEncodedQuery));
        console.log(res);
        return res
      }
  }
});

bnfMatches.initialize();

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
},
{
    name: 'states',
    displayKey: 'id',
    source: bnfMatches.ttAdapter()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

<select id="numerator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="numeratorId" class="typeahead" type="text" />
<br/>
<select id="denominator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="denominatorId" class="typeahead" type="text" />


谢谢。这是一种方法,它可以工作。如果可能的话,传递一个值会更好,但如果不可能,那就不可能了! - Richard
不用客气 :) 不确定是否正确理解了“如果可能的话最好传递一个值”?replace函数没有实现期望的模式吗?没有返回预期结果? - guest271314
我指的是replace函数中第二个参数的值与带有特定ID的DOM元素绑定。这通常是JS中要避免的,因为将JS直接与HTML绑定会使代码变得脆弱。 - Richard

2
Bloodhound的`replace`可以这样使用
replace: function (url, query) {
   if(_el.val() === "users"){
     return url + '/users?q=' + query;
   }else{
     return url + '/repositories?q=' + query;
   }
}

这是完整的例子。在这个例子中,我使用了 Github 的公共 API。选择下拉菜单用于在用户和仓库之间切换。
var make_dataset = function (el) {
    var _el = el; // nearest select for input
    var bloodhound = new Bloodhound({
        datumTokenizer: function (datum) {
            return Bloodhound.tokenizers.whitespace(datum.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'https://api.github.com/search',
            filter: function (users) {
                return $.map(users.items, function (user) {
                    return {
                        value: user.url
                    };
                });
            },
            replace: function (url, query) {
                if (_el.val() === "users") {
                    return url + '/users?q=' + query;
                } else {
                    return url + '/repositories?q=' + query;
                }
            }
        }
    });
    bloodhound.initialize();

    var dataset = {
        source: bloodhound.ttAdapter(),
    }

    return dataset;
}

/* initial setup */
$('.typeahead').each(function () { // each input
    var select = $(this).siblings('select'); // select near each input
    $(this).typeahead({
        hint: true,
        highlight: true,
        minLength: 2
    }, make_dataset(select)); // make_dataset initializes a bloodhound instance
});

这是完整的DEMO 希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接