【问题标题】:Using $(this) inside a method在方法中使用 $(this)
【发布时间】:2016-02-13 20:57:07
【问题描述】:

我在多个输入中使用 typeahead.js 方法 typeahead,我需要将所选值添加到当前输入附近的隐藏输入中。

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

$(this) 在这种情况下不起作用。

我创建了一个例子:https://jsfiddle.net/hvwy6a5n/

【问题讨论】:

  • 您能检查一下this 指向的内容吗?此外,如果可能,请以JSFiddleCodePen 的形式分享样本
  • 全局存储 $input 对象,用户 $input.next() 而不是 $(this).next() 怎么样?
  • alert($input) 未定义?
  • 或者您很可能只使用$input.next() 而不进行其他更改
  • @Rajesh Guys,请参阅 JSFiddle 示例。

标签: javascript jquery typeahead.js


【解决方案1】:

您可以尝试以下方式:Updated Fiddle

注意,.next() 将不起作用。 Typeahead 会更改您的 DOM 结构,您需要进行相应的导航。

  • this 代表Typeahead
  • this.$element.context 这将为您提供当前的输入。

这将为您提供下一个输入

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

【讨论】:

    【解决方案2】:

    您没有提到 this 是否指的是其他对象,即 typeahead 或 thisundefined。如果未定义(我的猜测),则需要将其与 afterSelect 绑定。

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

    【讨论】:

    • $(this) 引用一个预先输入的对象。请参阅上面的 JSFiddle 示例。
    猜你喜欢
    • 2019-04-21
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多