2010-08-03 62 views
1

我正在使用它在新窗口中打開傳出鏈接,但是當目標 是圖像時,我想要將圖像alt顯示爲標題。jQuery:ahref標題img 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」)的最簡單方法是什麼?

+0

你的意思是''標籤之間有''標籤嗎? – 2010-08-03 12:06:27

+0

是的,如:foo PHearst 2010-08-03 15:17:06

回答

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); 
}); 
0

從它聽起來像你鏈接到您想要在外部窗口中顯示的圖像。當您使用圖像作爲定位標記的目標時,它會引用實際圖像文件,而不是img元素,因此沒有與其關聯的alt標記。另一方面,如果圖像包含在錨點中,並且您單擊它以打開一個新窗口,那麼@ Nick的解決方案應該可以解決這個問題。 。