Qtip Ajax 请求在第一次悬停时不工作

Qtip Ajax Request not working on first hover

我想在鼠标悬停在元素上时显示 ajax 加载的内容,我正在使用 qTip 来实现此目的,但它仅在我第二次悬停时才有效。

$(document).on('mouseenter', 'span', function(){
if(!$(this).data('qtip')){
    $.ajax({
        context : this,
        url     : '/', 
        success : function(html) {
            $(this).qtip({
                content: "..now it works.",
                position: {
                    my: 'top left',
                    target: 'mouse',
                    //viewport: $(window), // Keep it on-screen at all times if possible
                    adjust: {
                        x: 10,  y: 10
                    }
                },
            });
        },
        error   : function(err){
            console.log(err.reponseText);
        }
    }); 
}

}); 这是我的 fiddle.

首先 - 这里最简单的解决方案是使用 qtip Ajax plugin - 所以你不需要处理它。

但是,只是为了解释您的代码出了什么问题 - 问题是您仅在第一次将鼠标悬停在元素上时才初始化 qtip。

因此,您需要将代码分成 2 个部分:

qtip Init:(注意内容必须至少包含一个字符)

$('span').qtip({
  content: " ",
  position: {
    my: 'top left',
    target: 'mouse',
    //viewport: $(window), // Keep it on-screen at all times if possible
    adjust: {
      x: 10,  y: 10
    }
  },
});

实际的 mouseenter 事件,它使用 qtip API (http://qtip2.com/api)

更改 qtip 'content'
$(document).on('mouseenter', 'span', function(){
        $.ajax({
        context : this,
        url     : '/', 
        success : function(html) {        
            $(this).qtip('option', 'content.text', 'response');
        },
        error   : function(err){
            console.log(err.reponseText);
        }
    }); 
});