2012-01-30 68 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); 

}