<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="./jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var btn1Ele=document.getElementById("btn1");
/**第一种方式**/
//btn1Ele.addEventListener("click",function(event){console.log("helloworld......");},false);
/**第一种方式**/
btn1Ele.addEventListener("click",helloworld,false);
});
function helloworld(){
console.log("helloworld......");
}
</script>
</head>
<body>
<p>js绑定事件</p>
<button id="btn1">测试按钮</button>
</body>
</html>
所需jquery 文件: jquery-1.11.1.min.js
一、监听机制的使用方法
添加事件监听的两种方法:attachEvent和addEventListener
二、attachEvent和addEventListener的区别
1.适应的浏览器版本不同
attachEvent方法, (ie系列)
addEventListener方法 Mozilla系列
2.同时在使用的过程中要注意事件不一样的地方
attachEvent方法 按钮onclick
addEventListener方法 按钮click
3.两者使用的原理:执行事件的优先级不一样
下面实例讲解如下:
var
btn1Obj = document.getElementByIdx_x_x_x_x_x_x_x_x_x_x_x_xx_x(“btn1″);
//object.attachEvent(event,function);
btn1Obj.attachEvent(“onclick”,method1);
btn1Obj.attachEvent(“onclick”,method2);
btn1Obj.attachEvent(“onclick”,method3);执行顺序为method3->method2->method1
addEventListener var btn1Obj =
document.getElementByIdx_x_x_x_x_x_x_x_x_x_x_x_xx_x(“btn1″);
//element.addEventListener(type,listener,useCapture);
btn1Obj.addEventListener(“click”,method1,false);
btn1Obj.addEventListener(“click”,method2,false);
btn1Obj.addEventListener(“click”,method3,false);执行顺序为method1->method2->method3
4.删除事件的方法不一样
detachEvent(‘onclick’,func);//ie下使用删除事件func
removeEventListener(‘click’,func);//Mozilla下,删除事件func
转自:http://blog.sina.com.cn/s/blog_51048da70101elgd.html
参考: http://www.cnblogs.com/aji88/archive/2012/07/20/2600492.html