2012-11-27 133 views
3

真的很簡單,但我不能解決它。jQuery - 獲取圖像標題

如何獲得的圖像的標題下面的代碼中,從點擊周邊<a>

$(this,'img').attr('title'); 
<ul> 
    <li><a href="01.jpg"><img src="01_th.jpg" title="image_1" /></a></li> 
    <li><a href="02.jpg"><img src="02_th.jpg" title="image_2" /></a></li> 
    <li><a href="03.jpg"><img src="03_th.jpg" title="image_3" /></a></li> 
</ul> 
$(function(){ 
    $('li a').click(function(e) { 
     e.preventDefault(); 
     var img_href = $(this).attr('href'); 
     var img_title = $(this,'img').attr('title'); 
     alert(img_title); //undefined. 
    }); 
}); 
+0

我相信正確的語法是'$('img',this)'而不是其他方式。 –

回答

6

你必須將上下文作爲第二個參數找到:

$('img', this).attr('title'); 
+0

不相關 - 您能否提供使用$('element',this)的文檔...想要閱讀! – pmandell

+0

@pmandell在這裏你去:http://api.jquery.com/jQuery/#jQuery1 –

+0

感謝@RoryMcCrossan,我以前不知道這個選擇器。 – arunes

3

你可以得到IMG標題這樣

$(this).find('img').attr('title');