JavaScript之事件绑定多个序列执行方法

时间:2024-04-15 07:44:55
//一种事件绑定多个方法:以加载事件为例
function addEventLoad(func,isLog) {
var oldOnLoad = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldOnLoad();
func();
}
}
if(isLog != undefined && isLog == true)
console.info("[addEventLoad:SUCCESS]:" + func);
return this;
} //拓展:一个节点绑定多种事件
function addEvent(element,eventType,handle,bol){
if (typeof handle != 'function') {
throw new Error("[addEvent] func must be a function.");
} else{
if(element.nodeType){
throw new Error("[addEvent] arguments:'element' id not element node!");
} else {
if(element.addEventListener){ //如果支持addEventListener
element.addEventListener(eventType, handle, bol);
}else if(element.attachEvent){ //如果支持attachEvent
element.attachEvent("on" + eventType, handle);//IE8 以下
}else{ //否则使用兼容的onclick绑定
element["on" + eventType] = handle;
}
}
}
}

//拓展
function bind(element,eventType,fn){
if(element.addEventListener){
element.addEventListener(eventType, fn, false);
}else if(element.attachEvent){
element.attachEvent('on'+ eventType, fn);
}
console.log('[bind] bind success.');
}