设置数据内容并显示弹出窗口 [英] Setting data-content and displaying popover

查看:81
本文介绍了设置数据内容并显示弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

当我点击时,弹出窗口没有显示,但是如果我稍后将鼠标悬停在元素上,它将显示弹出窗口,但没有内容( data-content 属性)。如果我在 success 回调中放入 alert(),它将显示返回的数据。

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). If I put an alert() inside the success callback it will display returned data.

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

Any idea why is happening this? Thanks!

推荐答案

在您的成功回调中,不再受约束与 get_data_for_popover_and_display()的其余部分相同的值。

In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().

别担心! 关键字是毛茸茸的;误解它的价值是JavaScript中的一个常见错误。

Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.

你可以通过分配保持对这个的引用来解决这个问题。它变为一个变量:

You can solve this by keeping a reference to this by assigning it to a variable:

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

或者你可以写 var that = this; 并在任何地方使用 $(that)。更多解决方案和背景此处

Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.

这篇关于设置数据内容并显示弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆