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

Setting data-content and displaying popover

本文关键字:窗口 显示 置数据      更新时间:2023-09-26

我试图用jquery的ajax从资源中获取数据,然后我试图使用这些数据来填充引导程序弹出窗口,如下所示:

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

检索数据的功能是:

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

发生的情况是,当我单击时,popover不会显示,但如果我稍后悬停元素,它将显示popover,但没有内容(data-content属性(。如果我在success回调中放入一个alert(),它将显示返回的数据。

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

在成功回调中,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');
         }
    });
}

或者,您可以编写var that = this;并在任何地方使用$(that)。这里有更多的解决方案和背景。

除了上面的答案之外,不要忘记,根据$.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');
         }
    });
}