【问题标题】:jQuery: ahref title from underlying img altjQuery:来自底层 img alt 的 ahref 标题
【发布时间】:2010-08-03 12:01:12
【问题描述】:

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

【问题讨论】:

  • 你的意思是<a></a>标签之间有一个<img>
  • 是的,如:

标签: jquery attr


【解决方案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");
});

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

或者,另一种方法,使用你所拥有的(将选择器更改为高效),然后为包含图像的锚设置标题,如下所示:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多