先介绍js添加事件通用方法,具体内容如下
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p1">测试添加事件:firefox使用addeventlistener,ie使用attachevent<br>
点击此p标签,绑定了2个弹出事件</p>
<script>
function test1() {
alert("test1");
}
function test2(){
alert("test2");
}
//添加事件通用方法
function addevent(element,e,fn) {
//firefox使用addeventlistener,来添加事件
if(element.addeventlistener) {
element.addeventlistener(e,fn,false);
}
//ie使用attachevent,来添加事件
else {
element.attachevent("on"+e,fn);
}
}
window.onload = function(){
var element = document.getelementbyid("p1");
addevent(element,"click",test1);
addevent(element,"click",test2);
}
</script>
</body>
</html>
js绑定事件的常用方式:
绑定事件的方式:用事件属性绑定事件函数
优点:
1、完成行为的分离
2、便于操作当事对象,因为function是作为on***的属性出现的,可直接用this引用当事对象。
3、方便读取事件对象,事件触发时系统自动把事件对象传递给事件函数,已其一个来传
<?xml version="1.0" encoding="utf-8" ?>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>js事件绑定</title>
<script type="text/javascript">
window.onload=function(){
var k=document.getelementbyid('k').onclick=function(event){
var jj=document.getelementbyid('jj');
jj.style.top=event.clientx+'px';
jj.style.left=event.clienty+'px';
}
}
</script>
<style>
#k{width:60px;height:80px; background-color:#80ffff;}
#jj{width:60px ;height:80px;background-color:#ffff00;z-index:1000;position:absolute;}
</style>
</head>
<body>
<p id="k"></p>
<p id="jj"></p>
</body>
</html>
以上就是javascript用事件属性绑定事件函数用法详解 的详细内容。