2012-06-16 206 views
1

我有下面的代码(本例中为两个图像 - 但在现实中,它可以被复制N次:获得IMG标签的ID在jQuery的

<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标签会记录事件并显示一个带有数据的弹出窗口,这一切都正常。

但我需要获得具有鼠标向下的特定“图片”的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(); 
      } 
     }); 

再次,这工作得很好,但它只是给我的第一个“知情同意”的ID跨度无论点击哪个“PIC”跨度。我怎样才能得到当前'图片'跨度的ID字段...当使用按钮时鼠标结束的那个?

+2

'this.id',我建议。 –

+0

[在函数中获取点击元素的ID]的可能重复(http://stackoverflow.com/questions/2952767/get-id-of-clicked-on-element-in-function) –

回答

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

您将获得IMG的src。

+0

谢谢 - 完美的作品! – TIW

4

尝试:

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

或:

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

代替:

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

$(".pic")会给有类pic不是你

点击一个第一个div
+0

可能更好地使用'。 prop('id')'现在,或者只是'this.id'。 – Pointy

+0

@Pointy谢谢,我将它添加到anwser – mgraph

+0

谢谢你们,感谢 – TIW

1

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

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

2
var imgref =this.id; 

,因为这也是一个对象,$(本)被包装在另一个对象的对象;

+0

谢谢 - 我是否正确地说$(this)是指当前对象,不管它是什么? – TIW