句柄EventListener的简单运用(小白适用)
HTML代码(下方有效果图):
<!DOCTYPE HTML>
<HTML>
<head>
<title>句柄EventListener的运用</title>
<!--添加句柄中所需要的三个参数:
1.指定的是什么事件
2.要做的事(方法)或者是名称
3.暂时不用
-->
<!--句柄用处:
1.用于方便代码的修改,若不加句柄,修改一处代码名称则需要修改两处
2.句柄之间不会覆盖,不加句柄之后显示最后一次修改
-->
<meta charset="utf-8" />
<script type="text/javascript" src="new_file.js" ></script>
<link rel="stylesheet" href="../css/new_file.css" />
</head>
<body>
<h2>原始案例</h2>
<button id="btn" onclick="change()">button</button>
<script>
function change(){
alert("hello");
}
</script>
<h2>单个简单句柄案例</h2>
<button id="btn2">button2</button>
<script>
//添加句柄
document.getElementById("btn2").addEventListener("click",function(){
alert("word");
})
</script>
<h2>多个简单句柄案例</h2>
<button id="btn3">button3</button>
<script>
var x=document.getElementById("btn3");
//方法一:
// x.addEventListener("click",function(){
// alert("hello too");
// })
//方法二:
x.addEventListener("click",hello1);
function hello1(){
alert("hello1");
}
//x.addEventListener("click",function(){
//alert("world too");
//})
x.addEventListener("click",world2);
function world2(){
alert("world2");
}
x.removeEventListener("click",hello);//移除句柄
</script>
</body>
</HTML>
点击演示效果:
点击button按钮
点击button2按钮
点击button3按钮
无点击演示效果: