开发者

jQuery: ahref title from underlying img alt

I'm using this to open outgoing links in a new window, but when the target is an image, I want to display the image alt as the title.

 $("a[href*='http://']:not([href*='"+location.hostname+"']),
    [href*='https://']:not([href*='"+location.hostname+"'])")
            .addClass("external")
            .attr("target","_blank")
            .attr("title", "Open link in new window");
        });

What is the easiest way of adding this to the the .attr开发者_开发知识库("title")?


If the <img> is inside the anchor, you could do it like this;

$("a[href*='http://'], a[href*='https://']").not("[href*='"+location.hostname+"']").each(function() {
  var $this = $(this).addClass("external").attr("target","_blank");
  var img = $this.children('img[alt]');
  $this.attr("title", img.length ? img[0].alt : "Open link in new window");
});

There are a few changes here, your current selector looks at only <a> in the first http:// check, but then looks at all elements in your https:// check, so this will be much more efficient. Then we're checking if the current element has a <img> inside, if it does and it has an alt attribute we use that, otherwise we give it the default title.

Or, another method, use what you have (change the selector to be efficient though) and afterwards set the titles for anchors that contain images, like this:

$("a.external > img[alt]").each(function() {
  $(this).parent().attr("title", this.alt);
});


From what it sounds like, you are linking to an image that you want to display in an external window. When you use an image as the target of an anchor tag, it references the actual image file, not an img element, thus there is no alt tag associated with it. If, on the other hand, the image is contained in the anchor and you click it to open a new window, then @Nick's solution should do the trick. .

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜