在工具提示中显示图像

时间:2012-05-29 09:44:38

标签: jquery html tooltip

我正在使用tipsy plugin


enter image description here


如果某人悬停其链接,我想显示用户的图片。现在该链接有一个 id ,用于将图像存储在服务器中。例如,如果 id 4 ,那么图片将是 4.jpg ,所以我使用此代码显示工具提示:

$('.tipsy').tipsy({
        html: true,
        gravity : 'e',
        title: function() {
            var i=0;
            alert(++i + "   first");
            var imgPath='<img height="50" width="50" src="dp/' + $(this).attr('id') + '.jpg" />';
            try{
                imgPath=$(imgPath).error(function() {
                    alert(++i + "  middle");
                    //imgPath='<img height="50" width="50" src="dp/no-image.jpg" />';
                });
            }catch(err){
                alert('inside catch');
            }
            alert(++i + "   last");
            return imgPath; 
        }
    });

imgPath 永远不会出现&lt; img height =“50”width =“50”src =“dp / no-image.jpg”/&gt; 但技术上如果错误存在,那么它将需要 noimage.jpg 的值,但每次它向我显示带有src的img为&lt; id&gt; .jpg

还有一件事我注意到了......没有错误的顺序是:

  1. alert(++ i +“first”);
  2. 提醒(++ i +“last”);

    和错误的顺序是:

    1. alert(++ i +“first”);
    2. alert(++ i +“last”);
    3. alert(++ i +“middle”);
  3. 这是错误的,因为中间警告介于第一最后

    之间

2 个答案:

答案 0 :(得分:1)

我真的不知道为什么不会被抓住。但是对于工具提示上的任何动态内容,您可以尝试这些插件:

http://craigsworks.com/projects/simpletip/

http://jquery.bassistance.de/tooltip/demo/

希望有所帮助。

答案 1 :(得分:0)

由于某种原因,您的错误函数似乎是异步调用的。我不确定为什么会发生这种情况,可能是在jquery文档中,但你可以做的是使用ajax()函数强制进行同步检查

alert("first");
var imgPath; //not setting imgPath here
        try{ 
            //using ajax() instead of earlier code
            $.ajax({
                url: 'dp/' + $(this).attr('id') + '.jpg', //might need to give absolute path instead of relative one
                type: 'get',
                async:false, //making sync call to ensure this code is executed
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    imgPath='no-image.jpg'; //if image doesnt exists then set no-image
                    alert("middle-error");
                },
                success: function(data){
                    imgPath='dp/' + $(this).attr('id') + '.jpg'; //succes -set required                    
                    alert("middle-success");
                }
            });
        }catch(err){ 
            alert('inside catch'); 
        } 
alert(" last"); 

我们在这里做的是检查图像是否是dp / 4.jpg存在于服务器上。我们也通过设置sync

强制async:false这次打电话