- 论坛徽章:
- 0
|
动态添加事件,原来都是用内联标签添加事件,但是这样不符合结构分离的规范。所以要适应以下方法添加事件:
- 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 这个函数。 |
|