tags:

views:

21

answers:

1

Here is my code.

//generate a id
$(".slide_img_a").each(function(){
 $(this).attr("id","img"+(Math.round(Math.random()*100)))
});

// get id   
var img_id = $(".slide_img_a").attr("id");

// alert the id  
$(".slide_img_a img").hover(function(){
 alert(img_id);
});

The problem of this is I have a 5 images with the same class and random id. When I hover the image, the result is he can only alert the id of first image. I wanted to do is when I hover them they will alert thier own id's

+1  A: 

You can use this inside the event handler and find what you want that way, like this:

$(".slide_img_a img").hover(function(){
  alert($(this).closest(".slide_img_a").attr("id"));
});

This takes the image you hovered at the time of hover then uses .closest() to go up to the .slide_img_a container, and that is the element we're pulling the ID from.


For pre-1.3 versions of jQuery (since we know the <a> doesn't have the class) you can do this:

$(".slide_img_a img").hover(function(){
  alert($(this).parents(".slide_img_a:first").attr("id"));
});
Nick Craver
$(".slide_img_a").closest is not a function
Jordan Pagaduan
@Jordan - you can use .parents('.slide_img_a:first') instread for older versions of jquery.
Nick Craver