使用数据破折号属性初始化预输入源
Initialize typeahead source using data dash attributes
我的 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"。
还有另一种方法可以做到这一点,或者我需要为我拥有的每种类型定义一个初始化?
谢谢。
您可以初始化一个空的 typeahead 并使用 "typeahead:active" 事件来初始化它:
$("selector").typeahead()
.on("typeahead:active", 函数(){
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
});
}
请记住,当您 "destroy" 您的控件时,它会回滚到原始元素。所以有些东西可能会丢失,比如焦点。
另一个问题是这个事件将在新控件中再次触发。所以你需要解绑这个事件
我只是在激活之前遍历了 typeahead 元素然后:
$(".typeahead").each(function(){
var url = $(this).data("url");
$(this).typeahead(...);
})
我的 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"。 还有另一种方法可以做到这一点,或者我需要为我拥有的每种类型定义一个初始化?
谢谢。
您可以初始化一个空的 typeahead 并使用 "typeahead:active" 事件来初始化它: $("selector").typeahead() .on("typeahead:active", 函数(){ 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
});
}
请记住,当您 "destroy" 您的控件时,它会回滚到原始元素。所以有些东西可能会丢失,比如焦点。
另一个问题是这个事件将在新控件中再次触发。所以你需要解绑这个事件
我只是在激活之前遍历了 typeahead 元素然后:
$(".typeahead").each(function(){
var url = $(this).data("url");
$(this).typeahead(...);
})