2012-01-30 4 views
1

У меня есть код в моем html-корпусе.Как получить идентификатор изображения, выбранного в jQuery

<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> 

Когда бы ни было нажато изображение, я хочу знать этот идентификатор изображения.

<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.

И для всех других предупреждений я получаю неопределенный как выход.

Может ли кто-нибудь помочь мне, как я могу получить идентификатор изображения выбранного изображения.

Благодаря

+0

Что делать с длиной? – Mike

+0

Правильно отформатируйте свой код, чтобы другие могли его прочитать. –

ответ

0

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

+1

Пожалуйста, предоставьте больше кода, когда вы отвечаете на вопрос, чтобы обеспечить контекст. –

0

Внутри contactsAction, this будет относиться к 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 documentation и jQuery tutorials.

0

(this).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); 

} 
Смежные вопросы