事件的add几种方式
【摘要】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<met...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">我是按钮</button>
<script type="text/javascript">
var btn = document.getElementById("btn");
/*
方式一:
1.通过onxxx的方式来添加
注意点: 由于是给属性赋值, 所以后赋值的会覆盖先赋值
*/
/*btn.οnclick=function()
{
alert("cyg");
}
btn.οnclick=function()
{
alert("777");
}
let obj={};
obj.say=function()
{
console.log("888");
}
obj.say=function()
{
alert("999");
}
obj.say();
*/
/*
方式二:
2.通过addEventListener方法添加
注意点:
1.事件名称不需要添加on
2.后添加的不会覆盖先添加的
3.只支持最新的浏览器IE9
*/
/*btn.addEventListener("click",function()
{
alert("666");
});
btn.addEventListener("click",function()
{
alert("777");
});
*/
/*
方式三
3.通过attachEvent方法添加
注意点:
1.事件名称必须加上on
2.后添加的不会覆盖先添加的
3.只支持低版本的浏览器
*/
/* btn.attachEvent("onclick",function()
{
alert("666");
});
btn.attachEvent("onclick",function()
{
alert("6");
});*/
cygEvent(btn,"click",function()
{
alert("666");
});
cygEvent(btn,"click",function()
{
alert("666");
});
function cygEvent(ele, name, fn)
{
if(ele.attachEvent)
{
ele.attachEvent("on"+name,fn);
}
else
{
ele.addEventListener(name,fn);
}
}
</script>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
文章来源: blog.csdn.net,作者:贵哥的编程之路(陈业贵),版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq_37805832/article/details/108674856
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)