1

我正在使用它在新窗口中打开传出链接,但是当目标是图像时,我想将图像 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("title") 的最简单方法是什么?

4

2 回答 2

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);
});
于 2010-08-03T12:09:01.060 回答
0

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

于 2010-08-03T12:12:31.727 回答