我使用Twitter的引導2.1.1和jQuery 1.8.1的Typeahead組件Twitter的引導預輸入:獲取上下文/調用帶有'元素this`
我試圖從預輸入的內訪問該文本框元素updater
功能。這是我目前的代碼,它很好用:
$('#client-search').typeahead({
source: function (query, process) {
$.get(url, { query: query }, function (data) {
labels = [];
mapped = {};
$.each(data, function(i,item) {
mapped[item.label] = item.value;
labels.push(item.label);
});
process(labels);
});
}
,updater: function (item) {
$('#client-id').val(mapped[item]);
return item;
}
,items: 10
,minLength: 2
});
我在同一頁面上有許多typeahead搜索框。每個搜索框都有一個編號爲#xxx-search
的編號和一個對應的編號爲#xxx-id
的隱藏輸入。我想通過做這樣的事情再利用的一切相同的代碼:
$('#client-search, #endClient-search, #other-search').typeahead({
...
,updater: function (item) {
var target = $(this).attr('id').split('-')[0] + '-id';
$('#'+target).val(mapped[item]);
return item;
}
...
我認爲this
將引用文本框元素中使用,但顯然不是,因爲我得到一個未定義的錯誤螢火蟲:
$(this).attr("id") is undefined
當我使用this
代替$(this)
,我得到:
this.attr is not a function
誰能幫助使這個禾RK?
UPDATE:THE ANSWER,AND MORE!
感謝以下benedict_w的回答,不僅現在這個工作很完美,而且我在重用性方面也做得更好。
這裏是我的<input>
看看這樣的:
<input type="text" autocomplete="off"
id="client-search"
data-typeahead-url="/path/to/json"
data-typeahead-target="client-id">
<input type="hidden" id="client-id" name="client-id">
注意在搜索框中如何引用隱藏標識。這裏是新的JS:
$(':input[data-typeahead-url]').each(function(){
var $this = $(this);
$this.typeahead({
source: function (query, process) {
$.get($this.attr('data-typeahead-url'), { query: query }, function (data) {
labels = [];
mapped = {};
$.each(data, function(i,item) {
mapped[item.label] = item.value;
labels.push(item.label);
});
process(labels);
});
}
,updater: function (item) {
$('#'+$this.attr('data-typeahead-target')).val(mapped[item]);
return item;
}
,items: 10
,minLength: 2
});
});
使用此解決方案時,我得到的在下降「不確定」選項的顯示了下來。 – Xeoncross
@Xeoncross:自發布此問題後,bootstrap和jQuery都進行了多次更新。它可能不再與您正在使用的版本相關。 –