首页 文章

jquery使用相同的类生成id

提问于
浏览
0

这是我的代码 .

//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);
});

这个问题是我有5个具有相同类和随机id的图像 . 当我悬停图像时,结果是他只能提醒第一张图像的ID . 我想要做的是当我徘徊他们时他们会提醒他们自己的身份

1 回答

  • 1

    您可以在事件处理程序中使用 this 并找到您想要的方式,如下所示:

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

    这将拍摄您在悬停时悬停的图像然后使用.closest()上升到 .slide_img_a 容器,这是我们从中提取ID的元素 .


    对于jQuery之前的1.3版本(因为我们知道 <a> 没有类),你可以这样做:

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

相关问题