IE方式
attachEvent(事件名称, 函数),绑定事件处理函数
detachEvent(事件名称, 函数),解除绑定
DOM方式
addEventListener(事件名称,函数, 捕获)
removeEventListener(事件名称, 函数, 捕获)
何时使用事件绑定
绑定事件和this
绑定匿名函数,会无法删除
==============================================
e.g. if we put two in the same position, then it will only show the later one
window.onload = function () { alter('a');};
window.onload = function () { alter('b');};
--> it will only alter b
<input type="button" id="btn1" value="button">
window.onload = function ()
{
var oBtn = document.getElementById ('btn1');
/* the below two function could not work same time
oBtn.onclick = function ()
{ alert('a'); };
oBtn.onclick = function ()
{ alert('b'); }; */
// so we use // IE 7 //
/*
oBtn.attachEvent('onclick',function () {alert ('a');} );
oBtn.attachEvent('onclick',function () {alert ('b');} );
// FF Chrome IE 9//
oBtn.addEventListerner('click',function() {alert ('a');}, false);
oBtn.addEventListerner('click',function() {alert ('b');}, false);
*/
if ( oBtn.attachEvent)
{
oBtn.attachEvent('onclick',function () {alert ('a');} );
oBtn.attachEvent('onclick',function () {alert ('b');} );
}
else
{
oBtn.addEventListerner('click',function() {alert ('a');}, false);
oBtn.addEventListerner('click',function() {alert ('b');}, false);
}
}
======================================
function myAddEvent (obj, ev, fn)
{
if(obj.attachEvent)
{
obj.attachEvent('on'+ev,fn);
}
else
{
obj.addEventListener(ev,fn,false);
}
}
=======================================
attachEvent(事件名称, 函数),绑定事件处理函数
detachEvent(事件名称, 函数),解除绑定
DOM方式
addEventListener(事件名称,函数, 捕获)
removeEventListener(事件名称, 函数, 捕获)
何时使用事件绑定
绑定事件和this
绑定匿名函数,会无法删除
==============================================
e.g. if we put two in the same position, then it will only show the later one
window.onload = function () { alter('a');};
window.onload = function () { alter('b');};
--> it will only alter b
<input type="button" id="btn1" value="button">
window.onload = function ()
{
var oBtn = document.getElementById ('btn1');
/* the below two function could not work same time
oBtn.onclick = function ()
{ alert('a'); };
oBtn.onclick = function ()
{ alert('b'); }; */
// so we use // IE 7 //
/*
oBtn.attachEvent('onclick',function () {alert ('a');} );
oBtn.attachEvent('onclick',function () {alert ('b');} );
// FF Chrome IE 9//
oBtn.addEventListerner('click',function() {alert ('a');}, false);
oBtn.addEventListerner('click',function() {alert ('b');}, false);
*/
if ( oBtn.attachEvent)
{
oBtn.attachEvent('onclick',function () {alert ('a');} );
oBtn.attachEvent('onclick',function () {alert ('b');} );
}
else
{
oBtn.addEventListerner('click',function() {alert ('a');}, false);
oBtn.addEventListerner('click',function() {alert ('b');}, false);
}
}
======================================
function myAddEvent (obj, ev, fn)
{
if(obj.attachEvent)
{
obj.attachEvent('on'+ev,fn);
}
else
{
obj.addEventListener(ev,fn,false);
}
}
=======================================
END