javascript delegate函数

本文介绍了一种使用委托方式处理页面上带有特定ID前缀元素点击事件的方法。通过自定义的delegateEvent函数实现,该函数能够遍历DOM节点并检查是否符合预设条件,一旦匹配则触发相应的事件处理器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Usage:
// Target all links with an ID starting with "notice"
delegateEvent({nodeName:/^a$/i, id: /^notice/}, 'click', function(){
    alert(this.id);
});


function delegateEvent(props, type, handler) {
    
    var fn = function(e) {
        
            e = e || window.event;
            
            var target = e.target || e.srcElement,
                parent = target,
                p, prop, matches = false;
            
            do {
                
                matches = false;
                
                for (p in props) {
                    if (!props.hasOwnProperty || props.hasOwnProperty(p)) {
                        prop = props[p];
                        matches = prop.test ? prop.test(parent[p]) : prop === parent[p];
                    }
                }
                
                if (matches) {
                    return handler.call( parent, e );
                }
                
            } while ( parent = parent.parentNode );
            
            return true;
        
        },
        doc = document;
    
    if (doc.addEventListener) {
        
        doc.addEventListener( type, fn, false );
        
    } else {
        
        if (doc.attachEvent) {
            doc.attachEvent( 'on' + type, fn );
        } else {
            var origHandler = doc['on' + type];
            doc['on' + type] = function(e) {
                origHandler.call(this, e);
                fn(e);
            };
        }
        
    }
    
}

转载于:https://www.cnblogs.com/bluedream2009/archive/2010/08/23/1806865.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值