开发者

Using 'each' to get a link to insert into a jQuery tooltip

I'm using this tooltip from jquerytools:

  $("li img").tooltip({ position: "bottom right"});

and want to insert a link into it from an existing "More Info" link in the same li:

var morelink;
morelink = $(this).find("li a").attr("href");
$(".tooltip").append('<a href="' + morelink + '">More Info</a>');

here it is in a failed fiddle:

http://jsfiddle.net/na开发者_如何学Pythonthanbweb/tEVnt/

How do I chain the two together, or use .each , to get the right link into the tooltip?


This isn't particularly easy due to the way the tooltips are added and there doesn't appear to be a direct link between the object and the tooltip that is easy to pick up on.

What is slightly easier to to is something like this, add the link to the title, before it is made into a tooltip:

// add tooltip from jquerytools 
$("li img").each(function(){
    var obj = $(this);
    var link = obj.next('a').attr('href');
    if (link !== undefined) {
        var title = obj.attr('title');
        title = title+' <a href="' + link + '">More Info</a>';
        obj.attr('title', title);
    }
    obj.tooltip({ position: "bottom right",});
});
  • Go through each li which has an img
  • Get the next object which in your case is an anchor
  • Get the link from the anchor
  • Check the link is actually a link (there are some without a link)
  • If there was a link, add it to the title (which will become the tooltip)
  • Finally add the tooltip

See it working here


Your best bet would probably be to create your own tooltip for each image.

<img src="http://dummyimage.com/100/eee/444.jpg&text=image1">
<div class="tooltip">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tincidunt rhoncus risus sed rhoncus.</div>
<a title="permanent link" href="http://example.com/1.html">More Info</a>

Build the tooltip like:

$(".tooltip").each(function(){
    var obj = $(this);
    obj.append(obj.prev().attr("title"), obj.next().clone());
});

According to the jQuery-tools documentation, adding a .tooltip container right after the element sent to the plugin, should do the trick.


Put this code:

$.fn.outerHtml = function()
{
if (this.length)
{
var div = $('<div style="display:none"></div>');
var clone =
$(this[0].cloneNode(false)).html(this.html()).appendTo(div);
var outer = div.html();
div.remove();
return outer;
}
else
return null;
};

$('li').each(function(){
    $(this).children("img").attr("title", $(this).children("img").attr("title") + $(this).children("a").outerHtml());
});

Right before

$("li img").tooltip({ position: "bottom right"});

What this does is it creates a .outerHtml extension to jquery that allows you to get the complete html of an element. Then, we append it to the title BEFORE it gets turned into a tooltip.

I just tried it on your jFiddle and it works fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜