jQuery学习-事件之绑定事件(三)

时间:2021-08-21 04:29:09

在上一篇《jQuery学习-事件之绑定事件(二)》我们了解了jQuery的dispatch方法,今天我们来学习下handlers

方法:

handlers: function( event, handlers ) {

        var sel, handleObj, matches, i,

            handlerQueue = [],

            delegateCount = handlers.delegateCount,

            cur = event.target;//绑定委托事件的元素

        // Find delegate handlers

        // Black-hole SVG <use> instance trees (#13180)

        // Avoid non-left-click bubbling in Firefox (#3861)

        //委托事件过滤,符合条件的事件才会被加入事件队列中

        if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {

            /* jshint eqeqeq: false */

            for ( ; cur != this; cur = cur.parentNode || this ) {

                /* jshint eqeqeq: true */

                // Don't check non-elements (#13208)

                // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)

                /*

                 nodeTyp:

                     元素element             1

                     属性attr                2

                     文本text                3

                     注释comments            8

                     文档document            9

                 

                 * */

                if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {

                    matches = [];

                    for ( i = 0; i < delegateCount; i++ ) {

                        handleObj = handlers[ i ];

                        // Don't conflict with Object.prototype properties (#13203)

                        sel = handleObj.selector + " ";

                        if ( matches[ sel ] === undefined ) {

                            matches[ sel ] = handleObj.needsContext ?

                                jQuery( sel, this ).index( cur ) >= 0 :

                                jQuery.find( sel, this, null, [ cur ] ).length;//判断【当前元素】是否是【绑定委托事件元素】的子元素

                        }

                        if ( matches[ sel ] ) {

                            matches.push( handleObj );

                        }

                    }

                    if ( matches.length ) {

                        handlerQueue.push({ elem: cur, handlers: matches });//将符合条件的事件加入事件队列中

                    }

                }

            }

        }

        //将非委托事件加入事件队列

        if ( delegateCount < handlers.length ) {

            handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });

        }

        return handlerQueue;
    }

OK,到这里了,哈哈!