我的Twitter Typeahead.js运行良好,但我想通过数据参数传递'预取'或'远程'URL,使其更加模块化(DRY!)。
所以我的标记是:
<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来说很新,所以请随时告诉我所有这些我做错的事情!
提前致谢
的Al
答案 0 :(得分:2)
更好的是:
$(".typeahead").each(function(){
$(this).typeahead({
name: $(this).name,
remote: $(this).data('source')
});
});
答案 1 :(得分:1)
解决了它!!
我需要创建某种函数来在调用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;
}
我确信这不是最优雅的方式 - 随意纠正这个/在评论中改进它
您的标记(HTML)如下所示:
<input type="text" class="typeahead" data-source="http://{yoursite.com}/url/to/your/json" >
希望这有助于某人。
答案 2 :(得分:0)
好的找出了#34;正确的&#34;(?)答案。为了在单击时动态确定URL,您需要使用源语法,其中第一个参数是选项映射,第2个到第n个参数是DataSet选项的映射。
library(magrittr)
find_relationships <- function(known_nodes, d){
# takes a vector of ids, known_nodes, and data consist of ids, d
subset(d, A %in% known_nodes | B %in% known_nodes) %>%
unlist %>%
c(known_nodes) %>%
unique -> new_nodes
if(length(new_nodes) == length(known_nodes)){
return(new_nodes)
}
else{
Recall(new_nodes, d)
}
}
unique_ids <- unique(c(df$A, df$B))
results <- lapply(unique_ids, find_relationships, d = df) %>% unique