简体   繁体   English

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

[英]Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this: 我正在尝试使用jquery的ajax从资源中获取数据然后我尝试使用此数据来填充引导弹出窗口,如下所示:

$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);

and the function for retrieving data is: 并且检索数据的功能是:

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');
         }
    });
}

What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). 发生的事情是当我点击时弹出窗口没有显示,但是如果我稍后悬停元素它将显示弹出窗口,但没有内容( data-content属性)。 If I put an alert() inside the success callback it will display returned data. 如果我在success回调中放置一个alert() ,它将显示返回的数据。

Any idea why is happening this? 知道为什么会这样吗? Thanks! 谢谢!

In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display() . 在您的成功回调中, this不再绑定到与get_data_for_popover_and_display()的其余部分相同的值。

Don't worry! 别担心! The this keyword is hairy; this关键字很毛茸茸; misinterpreting its value is a common mistake in JavaScript. 误解其价值是JavaScript中的一个常见错误。

You can solve this by keeping a reference to this by assigning it to a variable: 您可以通过保持一个参考解决这个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');
         }
    });
}

Alternatively you could write var that = this; 或者你可以写var that = this; and use $(that) everywhere. 到处使用$(that) More solutions and background here . 更多的解决方案和背景在这里

In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such: 除了上面的答案,不要忘记根据$ .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');
         }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM