2012-06-16 203 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