- 绑定事件的第1种办法:
- 函数写在结构层里面
- 非常不好,使页面很混乱,行为与结构得不到分离
1
| <input type="button" onclick="func();">
|
绑定事件的第2种办法
- 好处:行为与结构开始分离
缺点:
- 第二种绑定方式中
- 只能给一个时间绑定一个处理函数
- 即.
onclick = fn1
;.onclick = fn2
最终的效果是onclick = fn2
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <select name="xueli" > <option value="">请选择学历</option> <option value="大学" >大学</option> <option value="中学">中学</option> <option value="初中">初中</option> <option value="小学">小学</option> </select>
<form action=""> <p>Email:<input type="text" name="email"> 姓名:<input type="text" name="ming" >
</p> </form>
|
1 2 3 4 5 6 7 8 9 10
| document.getElementsByTagName('select')[0].onclick= function (){ alert('嘻嘻');
}
document.getElementsByName('email')[0].onblur=function (){ alert('哈哈哈');
}
|
1 2 3 4 5 6 7 8 9 10 11 12
| window.onload = function(){ var d = document.getElementById('school'); function fn1(){ alert('hello'); } function fn2(){ alert('world'); }
d.onclick = fn1; d.onclick = fn2; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| window.onload = function(){ var d = document.getElementById('school'); function fn1(){ this.style.background = 'blue'; } function fn2(){ this.style.background = 'red'; } d.onclick = function (){ fn1(); fn2(); }
}
|
下面这种写法没有问题 但是给DOM树额外增加了两个变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| window.onload = function(){ var d = document.getElementById('school'); d.fn1 = function (){ this.style.background = 'blue'; } d.fn2 = function (){ this.style.background = 'red'; } d.onclick = function (){ this.fn1(); this.fn2();
}
}
|
不在使用onclick
1 2 3 4 5 6 7 8
| window.onload = function(){ var d = document.getElementById('school'); d.addEventListener('click',function () {alert('blue');this.style.background ='blue'}); d.addEventListener('click',function () {alert('red');this.style.background ='red'});
}
|
去除绑定 不能用匿名函数 匿名函数 当时产生 当时消失
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var fn1 = function () {alert('blue');this.style.background ='blue'}; var fn2 = function () {alert('red');this.style.background ='red'};
function adde(){ var d = document.getElementById('school');
d.addEventListener('click',fn1); d.addEventListener('click',fn2);
}
function reme(){ var d = document.getElementById('school');
d.removeEventListener('click',fn2); }
|
1 2 3 4 5
| <div id="school"> </div> <input type="button" value="加事件" onclick="adde();"> <input type="button" value="减事件" onclick="reme();">
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| var fn1 = function () {alert('blue');this.style.background ='blue'}; var fn2 = function () {alert('red');this.style.background ='red'};
function adde(){ var d = document.getElementById('school');
d.attachEvent('onclick',fn1); d.attachEvent('onclick',fn2);
}
function reme(){ var d = document.getElementById('school');
d.deltachEvent('click',fn2); }
|