在方法中使用 $(this)
Using $(this) inside a method
我在多个输入中使用 typeahead.js 方法 typeahead
,我需要将所选值添加到当前输入附近的隐藏输入。
var $input = $('.typeahead');
$input.typeahead({
...
afterSelect: function (item) {
$(this).next('.input-hidden').val(item.id);
}
});
但是 $(this)
在这种情况下不起作用。
我创建了一个示例:https://jsfiddle.net/hvwy6a5n/
您没有提到 this
是否指的是 typeahead 或 this
是 undefined
的其他对象。如果它没有定义 (My guess) ,那么你需要用 afterSelect
.
绑定它
var $input = $('.typeahead');
$input.typeahead({
...
afterSelect: function (item) {
$(this).next('.input-hidden').val(item.id);
}.bind(this)
});
你可以这样尝试:Updated Fiddle.
请注意,.next()
将不起作用。 Typeahead 会更改您的 DOM 结构,您将需要进行相应的导航。
this
表示Typeahead
this.$element.context
这将为您提供当前输入。
这将为您提供下一个输入
$(this.$element.context).parent().next().find(".typeahead")
我在多个输入中使用 typeahead.js 方法 typeahead
,我需要将所选值添加到当前输入附近的隐藏输入。
var $input = $('.typeahead');
$input.typeahead({
...
afterSelect: function (item) {
$(this).next('.input-hidden').val(item.id);
}
});
但是 $(this)
在这种情况下不起作用。
我创建了一个示例:https://jsfiddle.net/hvwy6a5n/
您没有提到 this
是否指的是 typeahead 或 this
是 undefined
的其他对象。如果它没有定义 (My guess) ,那么你需要用 afterSelect
.
var $input = $('.typeahead');
$input.typeahead({
...
afterSelect: function (item) {
$(this).next('.input-hidden').val(item.id);
}.bind(this)
});
你可以这样尝试:Updated Fiddle.
请注意,.next()
将不起作用。 Typeahead 会更改您的 DOM 结构,您将需要进行相应的导航。
this
表示Typeahead
this.$element.context
这将为您提供当前输入。
这将为您提供下一个输入
$(this.$element.context).parent().next().find(".typeahead")