设置数据内容并显示弹出窗口

lic*_*rna 3 javascript jquery twitter-bootstrap

我正在尝试使用jquery的ajax从资源获取数据,然后我尝试使用此数据来填充引导弹出窗口,如下所示:

$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
Run Code Online (Sandbox Code Playgroud)

并且检索数据的功能是:

get_data_for_popover_and_display = function() {
    var _data = $(this).attr('alt');
    $.ajax({
         type: 'GET',
         url: '/myresource',
         data: _data,
         dataType: 'html',
         success: function(data) {
             $(this).attr('data-content', data);
             $(this).popover('show');
         }
    });
}
Run Code Online (Sandbox Code Playgroud)

发生的事情是当我点击时弹出窗口没有显示,但是如果我稍后悬停元素它将显示弹出窗口,但没有内容(data-content属性).如果我alert()success回调内部放置它将显示返回的数据.

知道为什么会这样吗?谢谢!

a p*_*erd 11

在您的成功回调中,this不再绑定与其余部分相同的值get_data_for_popover_and_display().

别担心!该this关键字是毛; 误解其价值是JavaScript中的一个常见错误.

您可以通过将引用this分配给变量来保持引用来解决此问题:

get_data_for_popover_and_display = function() {
    var el = $(this);
    var _data = el.attr('alt');
    $.ajax({
         type: 'GET',
         url: '/myresource',
         data: _data,
         dataType: 'html',
         success: function(data) {
             el.attr('data-content', data);
             el.popover('show');
         }
    });
}
Run Code Online (Sandbox Code Playgroud)

或者你可以随处写作var that = this;和使用$(that).更多的解决方案和背景在这里.


Yan*_*nis 6

除了上面的答案,不要忘记根据$ .ajax()文档,你可以使用context参数来实现相同的结果,而不需要额外的变量声明:

get_data_for_popover_and_display = function() {
    $.ajax({
         type: 'GET',
         url: '/myresource',
         data: $(this).attr('alt'),
         dataType: 'html',
         context: this,
         success: function(data) {
             $(this).attr('data-content', data);
             $(this).popover('show');
         }
    });
}
Run Code Online (Sandbox Code Playgroud)