在 jQuery 中获取 IMG 标签的 ID

Obtaining the ID of an IMG tag in jQuery

本文关键字:标签 ID IMG 获取 jQuery      更新时间:2023-09-26

我有以下代码(在这种情况下是两个图像 - 但实际上,它可以复制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鼠标关闭事件 - 因此单击鼠标与哪个图像无关紧要,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。 如何获取当前"图片"跨度的 ID 字段...使用按下按钮时鼠标在上面的那个??

尝试:

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

或:

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

而不是:

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

$(".pic")将给出具有类的第一个div pic而不是您单击的

div
var imgref =this.id;

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

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

您将获得IMG的SRC。

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

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

相关文章: