Get id when loading a jquery function

1

I'm trying to get the id of an image by loading the page I'm not doing well here is my code

var id;
function get_id() {
 var id= this.id;
 $("#result").html(id)

}
$(document).ready(function(){


get_id()


})
<!DOCTYPE html>
<html>
<head>

<title>Obtener id</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body >
<div>
	<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTyyVHz8oYsN2jOMsL2Q-8so-HGNq2_wGwiuAPBkK9wtvsZRN8u" width="100" height="50" id="imagen_00" alt="" onload="javascript:get_id()"/>
  <div id="result"></div>
</div>
</body>
</html>
What am I doing wrong?     
asked by andy gibbs 15.08.2018 в 15:41
source

1 answer

0

What happens is that when you call the function you do not pass anything to it, therefore he does not know what object he is referring to, saying that it would be like this:

var id;
function get_id(campo) {
 var id= campo.id;
 $("#result").html(id)

}
$(document).ready(function(){


get_id()


})


<!DOCTYPE html>
<html>
<head>

<title>Obtener id</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body >
<div>
    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTyyVHz8oYsN2jOMsL2Q-8so-HGNq2_wGwiuAPBkK9wtvsZRN8u" width="100" height="50" id="imagen_00" alt="" onload="get_id(this)"/>
  <div id="result"></div>
</div>
</body>
</html>

where you call the function in the thml you pass the value of the elememto with the this

I hope it serves you ...

    
answered by 15.08.2018 / 15:47
source