【问题标题】:Initialize typeahead source using data dash attributes使用数据破折号属性初始化预输入源
【发布时间】:2015-10-13 11:44:50
【问题描述】:

我的 typeahead 元素有一些数据属性,这些属性定义了 url、字段和其他要发送到我的服务的参数。

我正在尝试在源函数中访问这些数据属性,但没有成功。

我的 typeahead 元素是这样定义的:

<input class="typeahead" type="text" data-url="some_url.json">

我的 javascript 初始化 typeahead 是这样的:

$("body").find('.typeahead').typeahead(null, {
    displayKey: 'name',
    source: getSource()        
})  

function getSource(){
    var my_url = ???????

    return new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
                url: my_url,
                wildcard: '%QUERY'
              }
        });
}

“getSource”函数中的“this”变量指向“window”。 还有另一种方法可以做到这一点,或者我需要为我拥有的每个类型定义一个初始化?

谢谢。

【问题讨论】:

    标签: javascript twitter-bootstrap typeahead.js


    【解决方案1】:

    我只是在激活之前遍历 typeahead 元素:

    $(".typeahead").each(function(){
        var url = $(this).data("url");
        $(this).typeahead(...);
      })
    

    【讨论】:

      【解决方案2】:

      你可以初始化一个空的 typeahead 并使用 "typeahead:active" 事件来初始化它: $("选择器").typeahead() .on("typeahead:active", function(){ var url = $(this).data("url");

            //destroy old typeahead
            $(this).unbind("typeahead:active"); 
            $(this).typeahead("destroy");
      
            //reconstruct typeahead again
            $(this).typeahead(null,
                {
                  displayKey: xxx,
                  source: url
                });
        }
      

      请记住,当您“销毁”控件时,它会回滚到原始元素。所以有些东西可能会丢失,比如焦点。

      另一个问题是这个事件将在新控件中再次触发。所以你需要解绑这个事件。

      【讨论】:

        猜你喜欢
        • 2013-07-31
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多