I know that there is many post about this topic but i dont know why it keeps return me "undefined".
html:
<div class="gridShortlist active" onclick="shortlist('1');">
<img src="../../images/shortlisted.png"/>
</div>
js:
function shortlist(intValue){
if (intValue == 1){
var src = $(this).find('img').attr('src');
console.log(src);
}
else if (intValue == 0){
alert("deactive");
}
}
I would like to return the src value of img, but not sure why it will only return undefined. Anyone can help to correct me?
I know that there is many post about this topic but i dont know why it keeps return me "undefined".
html:
<div class="gridShortlist active" onclick="shortlist('1');">
<img src="../../images/shortlisted.png"/>
</div>
js:
function shortlist(intValue){
if (intValue == 1){
var src = $(this).find('img').attr('src');
console.log(src);
}
else if (intValue == 0){
alert("deactive");
}
}
I would like to return the src value of img, but not sure why it will only return undefined. Anyone can help to correct me?
Share Improve this question asked Oct 1, 2014 at 3:56 youaremysunshineyouaremysunshine 3517 gold badges17 silver badges28 bronze badges 3-
4
Can you provide more of your code? Based on that snippet, it looks like
this
is referring to thewindow
. – Dom Commented Oct 1, 2014 at 3:59 - isnt the "this" should be referring to div.gridShortlist since the onclick function is on it? – youaremysunshine Commented Oct 1, 2014 at 4:02
-
1
You should avoid binding onClick inline — try using jQuery's
.click()
instead? – Terry Commented Oct 1, 2014 at 4:06
3 Answers
Reset to default 2By passing this
with the click, we can make sure the right this
is used. Also, passing 1 as a number instead of a string is probably a good idea since you pare to a number.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://code.jquery./jquery-1.11.0.min.js"></script>
</head>
<body>
<div class="gridShortlist active" onclick="shortlist(this, 1);">
<img src="../../images/shortlisted.png"/>
</div>
<script>
function shortlist(_this, intValue){
if (intValue == 1){
var src = $(_this).find('img').attr('src');
console.log(src);
}
else if (intValue == 0){
alert("deactive");
}
}
</script>
</body>
</html>
You can check this link reference and jsFiddle
var ele=document.getElementById("id1");
ele.onclick =function (){
var intValue=1
if (intValue == 1){
var src = $(this).find('img').attr("src");
alert(src);
}
else if (intValue == 0){
alert("deactive");
}
};
div{
display:block;
background-color:red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gridShortlist active" id="id1" >
<img src="../../images/shortlisted.png"/>
</div>
You can do a simple jquery solution for the same by the following code:
$(document).on('click', '.gridShortlist', function (intValue) {
var src = $(this).find('img').attr('src');
console.log(src);
});
Working Fiddle
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744993358a4605040.html
评论列表(0条)