<button id="btn">click</button>var btn=document.getElementById('btn');The first type:
btn.onclick=function(){alert('hello world');}Eliminate event: btn.onclick=null;//The box will not pop up
The second type:
btn.addEventListener('click',function(){alert('hello world')},false); btn.addEventListener('click',function(){alert(this.id)},false);The third type:
function demo(){ alert('hello');}<button id="btn" onclick="demo()">click</button>The following is a guide to the js trigger button click event
Simulate JS trigger button click function
<html> <head> <title>usually function</title> </head> <script> function load(){ //The following two methods have the same effect as 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>Remark:
btnObj.click() is a real use program to click the button, triggering the button's onclick() event
btnObj.onclick() simply calls the method pointed to by btnObj's onclick, just calls the method and does not trigger the event