【问题标题】:how to attach a callback to Bootstrap Typeahead plugin如何将回调附加到 Bootstrap Typeahead 插件
【发布时间】:2012-06-08 07:05:17
【问题描述】:

使用自定义引导插件实现预输入功能 https://gist.github.com/1891669

如何为“选择”事件附加回调? 以下代码不起作用。

var selectedFn = $('.typeahead dropdown-menu').on('select', function( ev ){
    console.log(ev);
});

有人能解释一下这是如何工作的吗?

【问题讨论】:

    标签: jquery-ui jquery-plugins jquery-selectors twitter-bootstrap typeahead


    【解决方案1】:

    您可以像这样收听您的输入更改事件:

    $('input.typeahead').on('change', function () { ... })

    【讨论】:

    • 输入仅在输入失去焦点时触发更改事件。
    • 这似乎是唯一对我有用的东西,谢谢!
    【解决方案2】:

    这样做的新方法是:

    $('.input').typeahead({ 
        // snip
    }).on('typeahead:selected', function() {
        // on selected
    });
    

    【讨论】:

    • 这很棒,+1 因为这对我有用。你能解释一下为什么这个文档说它的 typeahead:select 当它真的 typeahead:selected 时? github.com/twitter/typeahead.js/blob/master/doc/…
    • 不,这在 13 年是正确的,也许开发版本中的 api 发生了变化?
    【解决方案3】:
    $('#myselector').typeahead({
    itemSelected:function(data,value,text){
       console.log(data)
        alert('value is'+value);
        alert('text is'+text);
    },
    //your other stuffs
    });
    

    您只需在回调函数中传递 itemSelected,它就会为您提供所选项目。

    希望这对你有用。

    【讨论】:

      【解决方案4】:

      在处理事件的函数中指定参数,以便按照https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#custom-events 文档中的建议选择值

      .on('typeahead:select', function(ev,value) {
              //value = the selected object
              //e.g.: {State: "South Dakota", Capital: "Pierre"}
          })
      

      使用 typeahead:select 而不是 typeahead:selected 给出完全相同的结果。我宁愿选择记录在案的那个。

      【讨论】:

        【解决方案5】:
        $('.typeaheadGroupSelect').typeahead({ 
            // snip
        }).on('typeahead:selected', function(data, value, text) {
            // on selected
            console.log(data);
            console.log(value.idPublic); // here you can access all json object by using value.key
            console.log(value.name);
        });
        

        我使用上面的代码 sn-p 从选择中访问数据并将某些隐藏值分配给另一个输入。

        在我向数据源添加一个对象之前 typeahead 用于查询数据,见下文:

        var jsonData = [
                {"id":"1","idPublic":"978343HFJ","name":"Volkswagen Group Sales International"},
                {"id":"2","idPublic":"8343JJR98","name":"BMW Group Sales APAC"},
                {"id":"3","idPublic":"935723JFF","name":"Jaguar Group Sales Asia"},
                {"id":"4","idPublic":"3243JFUFF","name":"Mercedes Benz Group Sales Europe"}
            ];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-21
          • 2015-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-31
          相关资源
          最近更新 更多