【问题标题】:How do I get 'this' in this function?我如何在这个函数中得到“这个”?
【发布时间】:2012-08-18 11:38:59
【问题描述】:

抱歉,我的 javascript-fu 不够好,无法提出更好的问题。

我正在使用 bootstrap (bootstrap-typeahead.js) 的 typeahead 功能,但由 Gudbergur Erlendsson here 添加了修改。

我正在使用 onselect 功能,并希望像这样(使用咖啡脚本)操作在这里输入的输入(我知道这个措辞真的很糟糕);

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

显然这不起作用,因为this 不在 onselect 函数的范围内,但我怎样才能得到它呢?我希望这是有道理的。

【问题讨论】:

  • 不会$(obj).css('background-color','blue') 做你想要的吗?
  • @Mahn: AFAIK obj 将被选中,而不是 <input>

标签: javascript jquery twitter-bootstrap coffeescript


【解决方案1】:

the gist,我们看到:

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)))

如果你跟踪它,你会发现你的回调中应该有一个this.$element,所以:

onselect: (obj) ->
    // AFAIK, 'obj' is the thing you selected
    @$element.css('background-color', 'blue')

应该是你要找的。​​p>

【讨论】:

  • 这是一个很棒的演练,谢谢!您刚刚开车回家,我的 javascript 知识有多糟糕。我现在无法按照你的建议让它工作,但我想我可能在我的代码中破坏了其他一些东西,所以我会继续尝试。我非常感谢在这里付出的努力。
  • 如果我改变选择我似乎成功了:拥有 this.onselect(val, this.$element) 和我的回调 onselect: (obj, elem) -> elem.css('背景颜色','蓝色')
  • @brad:这很有趣,我不知道代码会如何发生这种情况,但这不是代码第一次撒谎:) console.log(@) 在你的@ 中是什么样子987654328@回调?有@$element吗?
【解决方案2】:

如果this在onselect函数的范围外,但不在函数的范围内,则在函数外执行that = this,则可以在函数内引用that而不是this。如果您有兴趣,请在此处阅读有关that 的更多信息:Private Members in JavaScript

例如:

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

【讨论】:

    猜你喜欢
    • 2016-04-16
    • 2018-01-05
    • 2019-12-05
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多