Writing Method of Click Event in JavaScript

  • 2021-07-01 06:22:35
  • OfStack


<button id="btn">click</button>
var btn=document.getElementById('btn');

Type 1:


btn.onclick=function(){
alert('hello world');
}

Elimination event: btn. onclick = null; //It won't pop up

Type 2:


btn.addEventListener('click',function(){alert('hello world')},false);
btn.addEventListener('click',function(){alert(this.id)},false);

Type 3:


function demo(){

    alert('hello');
}
<button id="btn" onclick="demo()">click</button>

Let's introduce the js trigger button click event

Simulate JS trigger button click function


<html> 
  <head> 
    <title>usually function</title> 
  </head> 
  <script> 
function load(){ 
  // The effects of the following two methods are 1 Like  
  document.getElementById("target").onclick(); 
  document.getElementById("target").click(); 
} 
function test(){ 
  alert("test"); 
} 
</script> 
  <body onload="load()"> 
    <button id="target" onclick="test()">test</button> 
  </body> 
<html>  

Remarks:

btnObj. click () is really a program that clicks a button and triggers the onclick () event of the button

btnObj. onclick () simply calls the method pointed to by onclick of btnObj, simply calls the method, and does not fire an event


Related articles: