简体   繁体   中英

Passing the selected element to a named click event handler function without using anonymous function

I want to use the following to apply a hover event to multiple list items in a menu using the 'on' selector filter like this:

$('.menu').on( 'mouseenter mouseleave', 'li.parent', hoverHandler );

var hoverHandler = function(event) {
    var $el = $(event.currentTarget);
    // Do some stuff with the selected element
}

I am able to access the selected element in the hoverHandler function using event.currentTarget (event.target does not work becuase it is the innermost element (an 'a' element). event.delegateTarget is the .menu and event.relatedTarget is the html element).

The problem is, the menu has sub-menus so some li.parent items are within other li.parents. The hover events bubble up such that when I hover over a sub-menu parent, the hover event for it as well as any of its relevant ancestors is also triggered.

It works properly if I use an anonymous function with 'this' but would prefer not to do it this way.

Any suggestions?

Update

Here is a link to the full code: http://jsfiddle.net/mdbfLud9/

On further testing the code does work if I remove the timeOut and stopPropagation but would like to keep the timeOut

Here is my solution. Working example located at http://jsfiddle.net/jyqsLacx/ :

var timer = false;

// Hide Submenus at startup
$( '.menu' ).find( 'ul' ).hide();

var hoverHandler = function ( event ) {

    var $el = $( event.currentTarget );
    var isParent = $el.hasClass('parent');

    if ( isParent || event.type === 'mouseenter' || event.type === 'mouseover') {
        clearTimeout( timer );
        timer = setTimeout( function () {
            // Contract any expanded siblings and their children
            $el.parent().find( 'li.parent' )
                .removeClass( 'hover' )
                .find( 'ul' )
                    .slideUp();
            if ( isParent ) {
                if ( event.type === 'mouseenter' || event.type === 'mouseover' ) {
                    // Expand sub menu
                    $el
                        .addClass( 'hover' )
                        .children( 'ul' )
                            .slideDown();
                }
            } else { // not a parent
                event.stopPropagation();
            }
        }, 200);
    }
};

$('.menu').on('mouseenter mouseleave', 'li', hoverHandler);

I could not find a solution with event delegation that targeted the parent li only. This solution essentially uses events on non-parent li to stop event propagation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM