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 usedfind
instead your proposal would work. ;) – coreyward Commented Jan 17, 2016 at 20:50
3 Answers
Reset to default 4Use $(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条)