Two good ways to get the event source in javascript event functions

  • 2020-03-30 02:23:15
  • OfStack

In javascript's event response, there are many cases where we need to obtain the event source object to make changes to its properties, such as changing the SRC property of img. There are two methods to obtain the event source in the event response function:

The first:

Pass it directly in as a parameter. For example,
 
<div id="myid" onclick="show(this);">text</div> 

<script type="text/javascript"> 
function show(obj){ 
window.alert(obj.id); 
} 
</script> 

The second:

Simply drop the hidden event object. The event object has a srcElement attribute that you can access directly
 
<div id="myid" onclick="show();">text</div> 

<script type="text/javascript"> 
function show(){ 
window.alert(event.srcElement.id); 
} 
</script> 

Related articles: