gpt4 book ai didi

javascript - 如何在此函数中获取 'this' ?

转载 作者:行者123 更新时间:2023-12-02 19:26:15 24 4
gpt4 key购买 nike

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

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

我正在使用 onselect 功能,并且想要操作在这里输入的输入(我知道这真的措辞很糟糕),就像这样(使用 CoffeeScript );

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

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

最佳答案

来自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')

应该是您要找的。

关于javascript - 如何在此函数中获取 'this' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com