jQuery:来自底层img alt的ahref标题

时间:2010-08-03 12:01:12

标签: jquery attr

我正在使用它在新窗口中打开传出链接,但是当目标时 是一个图像,我想显示图像alt作为标题。

 $("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");
        });

将此添加到.attr(“标题”)的最简单方法是什么?

2 个答案:

答案 0 :(得分:1)

如果<img>在锚点内,你可以这样做;

$("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");
});

此处有一些更改,您当前的选择器仅在第一个<a>检查中查看http://,但随后查看https://中的所有元素检查,这样效率会更高。然后我们检查当前元素是否在内部有<img>,如果有,并且它具有我们使用的alt属性,否则我们给它默认标题。

或者,另一种方法,使用你拥有的东西(虽然改变选择器效率)然后设置包含图像的锚点的标题,如下所示:

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

答案 1 :(得分:0)

从听起来,您要链接到要在外部窗口中显示的图像。当您使用图像作为锚标记的目标时,它会引用实际的图像文件,而不是img元素,因此没有与之关联的alt标记。另一方面,如果图像包含在锚点中并且您单击它以打开一个新窗口,那么@ Nick的解决方案应该可以解决问题。             

相关问题