- 有必要限制一个页面中事件处理程序的数量,数量太多会导致大量内存,而且也会让用户更加页面反应不够灵敏。
- 建立在事件冒泡机制之上的事件委托技术,可以有效减少事件处理程序的数量。
<div id="box">
<input type="button" id="add" value="添加" />
<input type="button" id="remove" value="删除" />
<input type="button" id="move" value="移动" />
<input type="button" id="select" value="选择" />
</div>
<script>
window.onload = function(){
var Add = document.getElementById("add");
var Remove = document.getElementById("remove");
var Move = document.getElementById("move");
var Select = document.getElementById("select"); Add.onclick = function(){
alert('添加');
};
Remove.onclick = function(){
alert('删除');
};
Move.onclick = function(){
alert('移动');
};
Select.onclick = function(){
alert('选择');
} }
</script>- 核心:利用冒泡原理,将事件绑定到父元素,减少内存消耗,提升性能;利用event属性找到事件源,将事件定位到具体元素上。
- 建议在浏览器卸载页面之前移除页面中的所有事件处理程序。
var btn=document.getElementById("btn");
EventUtil.addHandler(btn,"click",function(){
btn.onclick=null;
document.getElementById("div").innerHTML="processing...";
});解决方法: 手动移除