【问题标题】:Passing the URL to typeahead.js via data-url parameter通过 data-url 参数将 URL 传递给 typeahead.js
【发布时间】:2013-12-13 08:40:42
【问题描述】:

我的 Twitter Typeahead.js 运行良好,但我想通过数据参数传递“预取”或“远程”URL 使其更加模块化(干!)。

所以我的标记是:

<input class="typeahead" data-url="http://campaigndashboard.dev/ajax/con" />

我曾在 JQuery 中写过:

$('.typeahead').typeahead({
    name: $(this).data('name'),
    limit: 100,

    remote: { /* This works! */
         url: 'http://campaigndashboard.dev/ajax/con?q=%QUERY',
    },
    remote: {  /* This doesn't */
         url: $(this).data('url') + '?q=%QUERY',
    }
});

我以前使用过这种传递变量的方式,但我很困惑为什么这不起作用。如果 %QUERY 是“远程”,我也想附加它,但如果它是“预取”则不附加 - 对此有什么想法吗?

注意:我不想修改 URL 的 %QUERY 部分,所以我不考虑 replace() 函数。

对 Jquery 非常陌生,所以请随时告诉我所有这些我做错的事情!

提前致谢

阿尔

【问题讨论】:

  • 澄清一下,我在这里包含了两个“远程”行,但在实际代码中,我使用了一个或另一个
  • 您是否在 javascript 控制台中遇到错误?
  • 嗨@Pascamel。感谢您及时的回复。没有错误,我尝试包含一个 console.log() 但没有记录:.on('typeahead:opened',function(){ console.log('remote=', remote);})

标签: javascript jquery twitter-bootstrap twitter typeahead.js


【解决方案1】:

更好:

$(".typeahead").each(function(){
      $(this).typeahead({
          name: $(this).name,
          remote: $(this).data('source')         
      });
 });

【讨论】:

  • 谢谢史蒂夫!更整洁。
【解决方案2】:

解决了!!

在调用 typeahead 之前,我需要创建某种函数来收集数据属性。

这就是我所做的(如果其他人想知道的话):

$('.typeahead').each( function() {
    createTypeahead( this );
} );

function createTypeahead( selector ){
  var t = $( selector );
  //get all the data-atributes from the input tag
  var source = $(t).data('source');
  //etc etc (get as many vars as you like here)

  var retval = t.typeahead({
    prefetch: source,    //This is the var from above
    //etc etc
  });

  return retval;
}

我确定这不是最优雅的方式 - 请随时在 cmets 中更正/改进它

您的标记 (HTML) 如下所示:

<input type="text" class="typeahead" data-source="http://{yoursite.com}/url/to/your/json" >

希望这对某人有所帮助。

【讨论】:

  • 附言。如果您和我一样陌生,那么要使其正常工作,只需将 class='typeahead' 添加到您希望出现预输入的输入中。不要忘记指定 data-source="url",因为在此示例中没有回退。 &lt;input type="text" class="typeahead" data-source="http://{yoursite.com}/url/to/your/json" &gt;
  • 我也遇到了这个问题。我不敢相信这没有直接支持。我喜欢你的方法,但是如果在 #each 循环运行之后添加了一个预先输入的输入,它就不起作用了。
【解决方案3】:

好的,找到了“正确的”(?)答案。为了在点击时动态确定 url,您需要使用源语法,其中第一个参数是选项映射,第二个到第 n 个参数是 DataSet 选项的映射。

$(".typeahead").typeahead({}, {
  source: function(){
    var url = this.$el.parents(".twitter-typeahead").find(".typeahead").data().url
    ....ajax to your url...
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多