//通用套路函数
var log = console.log.bind(console)
//查找元素
var e = function(sel) {
return document.querySelector(sel)
}
//批量查找元素
var es = function(elements) {
return document.querySelectorAll(elements)
}
//监听事件函数
var bindEvent = function(element, event, callback) {
element.addEventListener(event, callback)
}
//给多个元素绑定事件
var bindEventAll = function(elements, event, callback) {
for (var i = 0; i < elements.length; i++) {
var element = elements[i]
element.addEventListener(event, callback)
}
}
//插入html文件
var insertContent = function(sel, html) {
sel.insertAdjacentHTML('beforeend', html)
}
绑定事件通用性方法:
//使用了函数原型的方法:
// 函数名.apply(this指向的对象,传入函数的参数))
function handler2(e) {
console.log(this);
console.log(e);
}
function createEventRegister() {
if (window.addEventListener) {
return function (ele,type,handler) {
ele.addEventListener(type,handler);
}
}else if (window.attachEvent) {
return function (ele,type,handler) {
ele.attachEvent('on'+type,function() {
handler.apply(ele,window.event);
// 函数名.apply(this指向的对象,函数实参)
});
}
}else{
return function (ele,type,handler) {
ele['on'+type] = handler;
}
}
}
var register = createEventRegister();
register(fatherDiv,'click',handler2);
网友评论