javascript - 当 div 清空时,Ajax 加载的弹出图像并不总是清除

标签 javascript jquery html css ajax

我制作了一个图像预览器,当您将鼠标悬停在该链接上时,它会弹出图像。它有效,但有时当我停止将鼠标悬停在链接上时,它会无法 .empty div。我偶尔会得到上一张图片、错误文本或两张图片。如果我再次悬停它是固定的。这种情况可能发生在 10% 的时间内。我也无法获得div的高度。不知道这个是不是也有关系。

$('<div/>',{
   'id' : 'popup'
    }).appendTo('body');

function showError() {
    $('<div/>').text('Picture Not Found').appendTo('#popup');
    $('#popup').show();
};


function getImage() {
        $.ajax({
        type: 'GET',
        url: link,
        error: function(){
            showError();
        },
        success: function(data) {
            var styleText = $('style', data).text();
            var imageRegex = /background-image: url\('[^']+/;
            var imageMatch = styleText.match(imageRegex);
            if (imageMatch) {
                var image = imageMatch[0].replace(/background-image: url\('/, ''); 
                $('#popup').append('<img src="' + image + '" style="padding:0px" alt="">');
            } else {
                showError();
            };

        }
     });
};

$('a').filter(function() {
    return /users\/\d+\/pictures/.test(this.href);
    }).removeAttr('title').hover(function(e) {

    link = this.href.replace('http://', 'https://');
    getImage();
    $('#popup').show();
    height = $('#popup').outerHeight();
    console.log(height);

    }, function() {
        $('#popup').empty().hide();

    })
});

最佳答案

看起来这是在快速通过链接时触发悬停事件的问题。似乎可以通过为悬停添加延迟来解决。

这是一个指向帮助指南的链接。 http://jelaniharris.com/2008/adding-a-delay-to-jquery-functions/

我还将它更改为用于错误消息的单独 div,这样我就可以更改图像的 src 而不是清空 div。我认为这会使它更快一些。

关于javascript - 当 div 清空时,Ajax 加载的弹出图像并不总是清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207103/

相关文章:

php - 单击 HTML 表格数据并插入到文本区域

javascript - 单击按钮如何运行 php 脚本

html - 需要一些帮助在我的导航上创建三级菜单

javascript - 如何让输入框同时输入数字和密码?

javascript - 使用 id 作为数组的名称 (jQuery)

javascript - jquery变形图像效果

javascript - 使用 D3JS 在圆弧内旋转文本

javascript - 使用for循环在HTML div中显示JSON内容

javascript - 不同的宽度导致不同的浏览器 $ ("#div1").width()?

javascript - <sup> 没有正常出现