在jQuery中按类名获取上一个输入和img元素不起作用

时间:2021-05-31 14:29:10

I am trying to get img and input but its only getting Input. Below is code, I have tried find, closest, prev noting working

我试图获得img和输入,但它只获得输入。下面是代码,我已经尝试过找到,最接近,最常见的工作

HTML

  <img src="/img/no-pic.jpg" alt="no-pic" id="profilePic-0" class="profilePic img-thumbnail" />
  <input class="profilePicUrl" id="yourDetails" name="pic" type="hidden" value="">

    <a href="javascript:void(0);" class="btn btn-primary btn-xs picUpload"> 
      <span class="glyphicon glyphicon-upload"></span> Upload Photo
    </a>

JS

$('a.picUpload').on('click', function(){
   var inputUrl = $(this).prev('input.profilePicUrl').attr('id'),
       pictureFrame = $(this).find('img.img-thumbnail').attr('id');

   console.log(pictureFrame);
   console.log(inputUrl);
   console.log($(this));
   //openWindow(inputUrl, pictureFrame);
});

Here is a jsFiddle for same scenario, please help I don't know what am doing wrong

这是一个相同场景的jsFiddle,请帮助我不知道做错了什么

2 个解决方案

#1


1  

You need to use .siblings() instead of .find() because the image is the sibling of clicked anchor, .find() is used to get the descendants of matched elements which is not applicable in your case:

您需要使用.siblings()而不是.find(),因为图像是单击锚点的兄弟,.find()用于获取匹配元素的后代,这在您的情况下不适用:

pictureFrame = $(this).siblings('img.img-thumbnail').attr('id');

Updated Fiddle

#2


0  

Use .prevAll() because the img is a previous sibling of the anchor not its descendant.

使用.prevAll()因为img是锚的先前兄弟而不是它的后代。

pictureFrame = $(this).prevAll('img.img-thumbnail').attr('id')

Demo: Fiddle

#1


1  

You need to use .siblings() instead of .find() because the image is the sibling of clicked anchor, .find() is used to get the descendants of matched elements which is not applicable in your case:

您需要使用.siblings()而不是.find(),因为图像是单击锚点的兄弟,.find()用于获取匹配元素的后代,这在您的情况下不适用:

pictureFrame = $(this).siblings('img.img-thumbnail').attr('id');

Updated Fiddle

#2


0  

Use .prevAll() because the img is a previous sibling of the anchor not its descendant.

使用.prevAll()因为img是锚的先前兄弟而不是它的后代。

pictureFrame = $(this).prevAll('img.img-thumbnail').attr('id')

Demo: Fiddle