点击事件的三种写法
- 直接在标签添加
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<button id="bt" onclick="showClick()">click</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
index.js
function showClick(){
alert("clicked");
}
- 方法二(onclick)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<button id="bt">click</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
index.js
var btn=document.getElementById("bt");
btn.onclick=function(){
alert("clicked");
}
/*
等价于:
var btn=document.getElementById("bt");
function showClick() {
alert("clicked");
}
btn.onclick=showClick;
*/
//去掉绑定的事件:btn.onclick=null;
- 方法三(click)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<button id="bt">click</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
index.js
var btn=document.getElementById("bt");
btn.addEventListener("click",function(){
alert("clicked");
},false);
//去除绑定:btn2.removeEventListener('click', showMsg, false);
事件触发顺序
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<button id="bt" onclick="showClick1()">click</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
index.js
var btn=document.getElementById("bt");
function showClick1() {
alert("由标签绑定的onclick触发");
}
function showClick2() {
alert("由click触发");
}
btn.addEventListener("click",showClick2,false);
在浏览器运行结果:
当点击id="bt"时,先执行onclick事件的方法showClick1(),再执行click事件的showClick2()方法;