我使用的是Twitter Bootstrap 2.1.1的Typeahead组件和jQuery 1.8.1
我试图从typeahead的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搜索框。每个搜索框都有一个id #xxx-search
和一个对应的id为#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
会引用正在使用的文本框元素,但显然没有,因为我在firebug中得到了一个未定义的错误:
$(this).attr("id") is undefined
当我使用this
而不是$(this)
时,我得到:
this.attr is not a function
有没有人能帮上忙呢?
更新:答案,还有更多!
多亏了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">
注意搜索框是如何引用隐藏的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
});
});
发布于 2012-09-14 03:44:26
您在另一个函数中,因此您需要在外部闭包中保存对元素的引用,然后可以将其传递到内部闭包的事件处理程序中。您可以使用$.each()
调用遍历选择器,每次都保存对元素(this)的引用--例如
$('#client-search, #endClient-search, #other-search').each(function() {
var $this = $(this);
$this.typeahead({
...
,updater: function (item) {
var target = $this.attr('id').split('-')[0] + '-id';
$('#'+target).val(mapped[item]);
return item;
}
...
});
发布于 2013-07-03 18:20:04
公认的答案是一个很好的答案,但只是想分享一个实际上不需要外部闭包的替代方案。我使用的是bootstrap v2.3.1,您可以从this.$element
获得输入。
例如:
$(':input[data-typeahead-url]').typeahead({
source: function (query, process) {
$.get(this.$element.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.$element.attr('data-typeahead-target')).val(mapped[item]);
return item;
}
,items: 10
,minLength: 2
});
https://stackoverflow.com/questions/12413594
复制相似问题