在jQuery中获取IMG标记的ID

时间:2012-06-16 11:46:42

标签: javascript jquery mouseevent html

我有以下代码(在这种情况下是两张图片 - 但实际上,它可以复制N次:

<figure title="" class="DragBox" dragableBox="true" style="opacity: 1;" id="thumb_1">
   <span class="pic" id='UAJ754'>
      <span class="imagewrap">&nbsp;</span>
    <span class="overlay">
      <a href="fulldata.php?UAJ754" class="popUpSimple" rel="thumb_1">Image Information</a>
    </span>
    <img src="/pics/UAJ754.jpg" alt="">
  </span>

  <figcaption class="AlbumFig_Caption">A picture caption.
  </figcaption>
</figure>
<figure title="" class="DragBox" dragableBox="true" style="opacity: 1;" id="thumb_2">
   <span class="pic" id='JB6732'>
      <span class="imagewrap">&nbsp;</span>
    <span class="overlay">
      <a href="fulldata.php?JB6732" class="popUpSimple" rel="thumb_2">Image Information</a>
    </span>
    <img src="/pics/JB6732.jpg" alt="">
  </span>

  <figcaption class="AlbumFig_Caption">A second picture caption.
  </figcaption>
</figure>

现在,具有'pic'类的跨度具有与之关联的jQuery mousedown事件 - 因此,无论点击哪个图像鼠标都无关紧要,pic标记将记录事件并显示一个弹出窗口有数据。一切正常。

但我需要获取鼠标按下的特定'pic'的ID标签,或者检索IMG的src以便我可以获取ID,因为这需要传递给弹出窗口以显示正确图片的正确信息。

我有以下JS代码:

            $(".pic").mousedown(function(e) {   

                var mouseX = e.pageX; 
                var mouseY = e.pageY;

            if (e.which === 3) {                    

               $('.infobox').css({'top':mouseY+'px','left':mouseX+'px'}).fadeIn();

               var imgref = $(".pic").attr('id');
               alert (imgref);

               return false;
            }else{
               $('.info').fadeOut();
            }
        });

同样,这很好用,但它只给了我第一个'pic'跨度的ID,无论点击哪个'pic'跨度。如何获取当前“pic”范围的ID字段...当用户按下按钮时鼠标结束的那个?

4 个答案:

答案 0 :(得分:4)

尝试:

var imgref = $(this).attr('id');

或:

var imgref = $(this).prop('id');

而不是:

var imgref = $(".pic").attr('id');

$(".pic")会给第一个包含pic类的div而不是您点击的那个

答案 1 :(得分:2)

var imgref =this.id;

因为这也是一个对象而$(this)将一个对象包装在另一个对象中;

答案 2 :(得分:1)

而不是使用var imgref = $(".pic").attr('id');

使用此:var imgref = $(this).attr('id');

答案 3 :(得分:1)

var imgref = $('img', this).attr('src');

你将获得IMG的src。