免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1065 | 回复: 0
打印 上一主题 下一主题

初学web-4 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-21 08:44 |只看该作者 |倒序浏览
动态添加事件,原来都是用内联标签添加事件,但是这样不符合结构分离的规范。所以要适应以下方法添加事件:
  • addEventListener和attachEvent方法
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function jump(){
    alert("Got it!");
}
window.onload = function(){
    if(window.attachEvent)//IE浏览器
    {
        document.getElementById("listener").attachEvent("onclick",jump);
    }
    else//其他浏览器
    {
        document.getElementById("listener").addEventListener("click",jump,false);
    }
}
</script>
</head>

<body>
<div>
    <input id="listener" type="button" value="listen" />
</div>
</body>
</html>
  • expando直接添加属性,缺点是如果为一个元素挂载多个event handler的话,后面的会覆盖前面。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload = function(){
    document.getElementById("click").onclick = function jump1(){
        alert("I'm 1.");   
    }   
    document.getElementById("click").onclick = function jump2(){
        alert("I'm 2.");   
    }
}
</script>
</head>

<body>
<input id="click" value="click" type="button" />
</body>
</html>

会把函数 jump1覆盖掉,只会执行jump2 这个函数。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP