javascript - On element click get img src attribute value - Stack Overflow

I have the following html <td class="emailModal" data-name="My name" data-id=&qu

I have the following html

<td class="emailModal" data-name="My name" data-id="myId" data-target="#myModal" data-toggle="modal">
  <div class="someClass">
    <img class="imgClass" width="50%" align="left" src="/Content/images/myImage.png">
  </div>
</td>

On the onclick event I'm fetching the data-name attribute value using js

var name = $(this).data('name');

My question is how to fetch the clicked image's src value using js

Among the things I've tried:

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

I have the following html

<td class="emailModal" data-name="My name" data-id="myId" data-target="#myModal" data-toggle="modal">
  <div class="someClass">
    <img class="imgClass" width="50%" align="left" src="/Content/images/myImage.png">
  </div>
</td>

On the onclick event I'm fetching the data-name attribute value using js

var name = $(this).data('name');

My question is how to fetch the clicked image's src value using js

Among the things I've tried:

var src = $(this).closest('img').attr('src');
Share Improve this question edited Jan 17, 2016 at 20:54 Madara's Ghost 175k50 gold badges272 silver badges314 bronze badges asked Jan 17, 2016 at 20:44 user1765862user1765862 14.2k34 gold badges135 silver badges247 bronze badges 2
  • You can't just refer img by its class?... – nicael Commented Jan 17, 2016 at 20:49
  • 1 @user1765862 closest looks up the ascendence chain; if you used find instead your proposal would work. ;) – coreyward Commented Jan 17, 2016 at 20:50
Add a ment  | 

3 Answers 3

Reset to default 4

Use $(this).find('img').attr('src'). Guessing the element click is the td element.

Add the following attribute to your element:

onclick="getImgSrc(this)"

Then add the following javascript:

function getImgSrc(param){
var imgSrc = $(param).attr("src");
};

You can now include this onclick event to any element on your website to get the img src :)

Please note that the above requires jQuery

I think you can do $(this).attr('src');

I have created a JSFiddle to illustrate my answer in practise:

https://jsfiddle/jagoldsmith/6jn5obx4/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745438202a4627708.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信