Как получить идентификатор изображения, выбранного в JQuery - PullRequest
1 голос
/ 30 января 2012

У меня есть код ниже в моем теле HTML.

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

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

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

Спасибо

Ответы [ 3 ]

0 голосов
/ 30 января 2012

Внутри 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 и jQuery руководства .

0 голосов
/ 30 января 2012

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

}
0 голосов
/ 30 января 2012

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...