【问题标题】:Twitter Bootstrap Typeahead - Add a "loading" class to the input when search beginsTwitter Bootstrap Typeahead - 搜索开始时向输入添加“加载”类
【发布时间】:2013-05-16 12:17:10
【问题描述】:

如何在触发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));
            }
        })
    }
});

【问题讨论】:

    标签: jquery twitter-bootstrap bootstrap-typeahead


    【解决方案1】:

    当您在 $.ajax 调用中时,这指的是 $.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 的对象中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 2012-12-07
      • 2013-05-28
      • 1970-01-01
      • 2016-07-29
      相关资源
      最近更新 更多