Twitter Bootstrap Typeahead - 当搜索开始时,将"loading"类添加到输入框

4

当ajax请求被触发时,我如何更改typeahead输入框的类,并在请求完成时删除该类?我不知道是否使用了正确的事件,我认为使用$(this)来引用输入框时对象范围有误。

$('.iof-subject').typeahead({
    source: function(typeahead, query) {
        $.ajax({
            url: window.app.ROOT + 'subjects/ajax/search_name',
            data: {name: query},

            // Add loading class to the text input (.iof-subject) when
            // the ajax request begins
            beforeSend: function() {
                $(this).addClass('loading');
            },

            // Remove loading class from text input (.iof-subject) when
            // the ajax request is complete
            complete: function() {
                $(this).removeClass('loading');
            },

            success: function(data) {
                return typeahead.process($.parseJSON(data));
            }
        })
    }
});
1个回答

4
当您在$.ajax调用内部时,this指的是$.ajax,而不是.iof-subject。
我会这样做。
source: function(typeahead, query) {
    //Create a copy of this, so code in $.ajax can access the variables
    var that = this;
    $.ajax({
        url: window.app.ROOT + 'subjects/ajax/search_name',
        data: {name: query},

        beforeSend: function() {
            //that.$element is a variable that stores the element the plugin was called on
            that.$element.addClass('loading');
        },

        complete: function() {
            that.$element.removeClass('loading');
        },

        success: function(data) {
            return typeahead.process($.parseJSON(data));
        }
    })
}

本插件将引用此内容,并将元素作为变量存储在名为$element的对象中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接