Javascript 如何在此函数中获取“this”?

Javascript 如何在此函数中获取“this”?,javascript,jquery,twitter-bootstrap,coffeescript,Javascript,Jquery,Twitter Bootstrap,Coffeescript,对不起,我的javascript不够好,无法提出更好的问题 我正在使用bootstrap-bootstrap-typeahead.js的typeahead特性,但经过Gudbergur Erlendsson添加的修改 我正在使用onselect功能,并且想要操纵这里输入的输入,真的很糟糕,我知道,就像使用coffeescript一样 $('form input').typeahead source: list onselect: (obj) -> $(this).css('

对不起,我的javascript不够好,无法提出更好的问题

我正在使用bootstrap-bootstrap-typeahead.js的typeahead特性,但经过Gudbergur Erlendsson添加的修改

我正在使用onselect功能,并且想要操纵这里输入的输入,真的很糟糕,我知道,就像使用coffeescript一样

$('form input').typeahead
  source: list
  onselect: (obj) ->
    $(this).css('background-color','blue')
显然,这不起作用,因为这不在onselect函数的范围内,但是我如何才能将它放到那里呢?我希望这是有意义的。

从中,我们看到:

var Typeahead = function ( element, options ) {
  this.$element = $(element)
这是:

select: function () {
  //...
  if (typeof this.onselect == "function")
      this.onselect(val)
$.fn.typeahead = function ( option ) {
    return this.each(function () {
        //...
        if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
这是:

select: function () {
  //...
  if (typeof this.onselect == "function")
      this.onselect(val)
$.fn.typeahead = function ( option ) {
    return this.each(function () {
        //...
        if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
如果您对此进行跟踪,您将看到回调中应该有一个this.$元素,因此:

onselect: (obj) ->
    // AFAIK, 'obj' is the thing you selected
    @$element.css('background-color', 'blue')
应该是您要查找的内容。

如果这在onselect函数的范围之外,但不在函数的范围之内,请在函数之外执行一个this=this,然后您可以在函数中引用它而不是this。如果您感兴趣,请在此处阅读更多信息:

例如:

that = this
$('form input').typeahead
  source: list
  onselect: (obj) ->
    $(that).css('background-color','blue')

$obj.css'background-color'、'blue'难道不能满足您的需求吗?@Mahn:AFAIK obj将是您选择的对象,而不是对象。这是一个很棒的演练,谢谢!你刚刚明白了我的javascript知识有多差。我现在不能像你建议的那样工作,但我想我可能破坏了代码中的其他一些东西,所以我会继续尝试。我真的很感谢你在这里付出的努力。如果我更改select:to have this.onselectval,this.$元素并回调到onselect:obj,elem->elem.css'background-color',blue'@brad:这很有趣,我不知道从代码中会发生什么,但这不是代码第一次撒谎:console.log@在onselect回调中是什么样子的?是否存在@美元元素?