用原生js在DOM元素上面添加方法

if (window.HTMLElement) {
    // 使用原型扩展DOM自定义事件
    
    HTMLElement.prototype.addEvent = function(type, fn, capture) {
        var el = this;
        if (window.addEventListener) {
            el.addEventListener(type, function(e) {
                fn.call(el, e);
            }, capture);
        } else if (window.attachEvent) {
            el.attachEvent("on" + type, function(e) {
                fn.call(el, e);
            });
        } 
    };
} else {
    // 如果是不支持HTMLElement扩展的浏览器
    // 通过遍历所有元素扩展DOM事件
    
    var elAll = document.all, lenAll = elAll.length;
    for (var iAll=0; iAll 
  
 
  
 
  
 
  
 
  
//--------- 以下是测试代码 -------------

document.getElementById("image").addEvent("click", function() {
    alert("这是:" + this.alt);    
});

你可能感兴趣的:(js)