2016-02-13 45 views
0

我在多個輸入中使用typeahead.js方法typeahead,我需要將選定值添加到當前輸入附近的隱藏輸入。

var $input = $('.typeahead'); 
$input.typeahead({ 
    ... 
    afterSelect: function (item) { 
     $(this).next('.input-hidden').val(item.id); 
    } 
}); 

$(this)在這種情況下不起作用。

我創建了一個例子:https://jsfiddle.net/hvwy6a5n/

+2

你可以查閱一下'this'指向。另外,如果可能,共享一個樣本作爲'JSFiddle'或'CodePen' – Rajesh

+0

全局存儲$ input對象和用戶$ input.next()而不是$(this).next()怎麼樣? – Piotrek

+0

警報($ input)未定義? –

回答

1

你可以嘗試這樣的事情:Updated Fiddle

注意,.next()將不起作用。 Typeahead改變你的DOM結構,你需要相應的導航。

  • this代表Typeahead
  • this.$element.context這會給你你的電流輸入。

這會給你下一個輸入

$(this.$element.context).parent().next().find(".typeahead") 
0

如果this指的是一些,其他對象的預輸入,或thisundefined你沒有提到。如果它沒有定義(我的猜測),那麼你需要將它與afterSelect綁定。

var $input = $('.typeahead'); 
$input.typeahead({ 
    ... 
    afterSelect: function (item) { 
     $(this).next('.input-hidden').val(item.id); 
    }.bind(this) 
}); 
+0

$(this)反射到一個前端對象。請參閱上面的JSFiddle示例。 – marcelo2605

相關問題