最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the closest img tag in jquery? - Stack Overflow

programmeradmin2浏览0评论

HTML

"+fileName+"

I need to change the image when the td with id=fileName is clicked in jQuery.

How can I fetch the img tag and change its src attribute using jQuery?

I am trying to do something like this :

$($(this).closest("img")).attr("src")

HTML

"+fileName+"

I need to change the image when the td with id=fileName is clicked in jQuery.

How can I fetch the img tag and change its src attribute using jQuery?

I am trying to do something like this :

$($(this).closest("img")).attr("src")
Share Improve this question edited Sep 12, 2022 at 8:08 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jun 17, 2013 at 18:21 VinayVinay 2372 gold badges8 silver badges17 bronze badges 1
  • Thanks so much for the quick replies ... helped me solve my issue :) – Vinay Commented Jun 17, 2013 at 21:06
Add a comment  | 

6 Answers 6

Reset to default 8

Use a combination of .closest and .find()

closest finds its ancestors

you need to find its descendants and not the ancestors

So you need to first find the closest row, which contains the filename id element and then find the img which is a descendant of the corresponding row

$(this).closest('tr').find("img").attr("src"); // using find

or

var $tr = $(this).closest('tr'); // get the closest row
$("img", $tr).attr("src");  // use a context to get the image

You could use .siblings()

JavaScript/jQuery

$(this).siblings("#img_id").children('img').prop('src');

Edit

JSFiddle proof

"the td with id=fileName is clicked": You are going to have to go up to the tr element, and then use find to search through the descendants in order to find the image element. .parentNode will find the parent element of this (the <td> in this case). find("img") will find the image tag contained in the first td element.

$($(this.parentNode).find("img")).attr("src")

You need to clean up your code a bit as you have a random <span> and the first <td> isn't closed. Your id's need to be wrapped in double quotes.

http://jsfiddle.net/pjdicke/tQ5vr/5/

<table>
   <tr class="test_file">
      <td id="img_id"><img src="http://www.abmuku.com/wp-content/uploads/2012/04/google-logo-small.jpg" /></td>
      <td colspan=2 id="fileName"><button>file name</button></td>
   </tr>
</table>

$('button').on('click', function(){
    $(this).closest('tr').find('td img').attr('src','http://atoralhistory.uconn.edu/images/Yahoo_logo_small.gif');
});

Try with this

$(this).siblings().find('img').prop('src','your_image_url');

DEMO

You have to replace the new_src variable.

$(function() {
   $('#fileName').on('click', function() {
      $(this).closest('tr').find('img').attr('src', new_src);
   });
});
发布评论

评论列表(0)

  1. 暂无评论