简体   繁体   English

如何在jquery中获取最接近的img标签?

[英]How to get the closest img tag in jquery?

HTML HTML

<tr class='test_file'>
    <td id=img_id><img src='"+ROOT_PATH+"/assets/arrow_black_right.png' /></td>
    <td colspan=2 id=fileName>"+fileName+"</td>
</tr><span>

I need to change the image when the td with id=fileName is clicked in jQuery. 我需要在jQuery中单击id = fileName的td时更改图像。

How can I fetch the img tag and change its src attribute using jQuery? 如何使用jQuery获取img标记并更改其src属性?

I am trying to do something like this : 我想做这样的事情:

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

Use a combination of .closest and .find() 使用.closest.find()的组合

closest finds its ancestors closest发现它的祖先

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 所以你需要先找到最近的行,其中包含filename id元素,然后find img ,它是相应行的后代

$(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() 你可以使用.siblings()

JavaScript/jQuery 的JavaScript / jQuery的

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

Edit 编辑

JSFiddle proof JSFiddle证明

"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. “单击id = fileName的td”:您将不得不转到tr元素,然后使用find搜索后代以查找图像元素。 .parentNode will find the parent element of this (the <td> in this case). .parentNode会发现的父元素this (该<td>在这种情况下)。 find("img") will find the image tag contained in the first td element. find("img")将找到第一个td元素中包含的图像标记。

$($(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. 您需要稍微清理代码,因为您有一个随机<span>并且第一个<td>未关闭。 Your id's need to be wrapped in double quotes. 你的id需要用双引号括起来。

http://jsfiddle.net/pjdicke/tQ5vr/5/ 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 DEMO

You have to replace the new_src variable. 您必须替换new_src变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM