jquery get generated id with the same class
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开发者_C百科 will alert thier own id's
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"));
});
精彩评论