2012-01-30 39 views
1

我在我的html正文中有以下代碼。如何獲取在jquery中選擇的圖像的ID

<ul> 
<li> 
<div> 
<a href=javascript:contactsAction() > 
<img src="contactimageloc1.jpg" id="image_id1 " width="140px" height="160px"/> 
</a> 
<br> 
firstName  lastName , title 
</div> 
</li> 
<li> 
<div> 
<a href=javascript:contactsAction() > 
<img src="contactimageloc.jpg" id="image_id2" width="140px" height="160px"/> 
</a> 
<br> 
firstName  lastName , title 
</div> 
</li> 
</ul> 

當有人點擊圖像時,我想知道圖像ID。

<script> 
function contactsAction(){ 

alert('On Image click function'+$(':image')); 
alert('Inside $(this).find(a:first).attr(id) :'+$(this).find('a:first').attr('id')); 

alert('image $(this).children(a).attr(id): '+$(this).children('a').attr('id')); 

alert('image $(this).children(a).eq(0).attr(id): '+$(this).children('a').eq(0).attr('id')); 

alert('$(this).children().length: '+ $(this).children().length); 
alert('image id: '+$(this).attr('id').value); 

} 
</script> 

對於alert('$(this).children().length: '+ $(this).children().length);我得到的輸出爲0

而對於所有其他警報我收到未定義作爲輸出。

任何人都可以幫助我如何獲得所選圖像的圖像ID。

感謝

+0

你對長度做了什麼? – Mike 2012-01-30 10:52:25

+0

請正確縮進您的代碼,以便其他人可以閱讀它。 – 2012-01-30 10:55:10

回答

0

$(this).children().attr('id')

+1

當您回答問題以提供背景時,請提供更多的代碼。 – 2012-01-30 12:41:16

0

裏面contactsActionthis將把window,因爲你在呼喚它的正常功能。

我建議給這些鏈接一個正確的URL並附加事件處理程序使用jQuery:

$('a').click(function(event) { // use an appropriate selector here 
    event.preventDefault(); // don't follow the URL 
    console.log('Image clicked: ' + $(this).children('img').attr('id')); 
}); 

請看看在jQuery API documentationjQuery tutorials

0

(this).id會給你有問題的元素的ID。

function contactsAction(
){ 

alert (this.id); //This will tell you the id of the element 

alert('On Image click function'+$(':image')); 
alert('Inside $(this).find(a:first).attr(id) :'+$(this).find('a:first').attr('id')); 

alert('image $(this).children(a).attr(id): '+$(this).children('a').attr('id')); 

alert('image $(this).children(a).eq(0).attr(id): '+$(this).children('a').eq(0).attr('id')); 

alert('$(this).children().length: '+ $(this).children().length); 
alert('image id: '+$(this).attr('id').value); 

}