简体   繁体   中英

JavaScript: DRY mouseover/mouseout event handlers

This is my code:

    $rows
        .on('mouseover', '.row', function () {
            $(this).find('.label').show();
        })
        .on('mouseout', '.row', function () {
            $(this).find('.label').hide();
        });

Can it be DRYed out?

You can bind both events, listen to event.name and then use jQuery.fn.toggle

$userRows.on('mouseover mouseout', '.row', function(event) {
    $(this).find(".label").toggle( event.name == "mouseover" );
});

Im pretty sure you can also use jQuery.fn.hover :

$userRows.on('hover', '.row', function(event) {
    $(this).find(".label").toggle( event.name == "mouseenter" );
});

or even:

$userRows.on('hover', '.row', function(event) {
    $(this).find(".label").toggle();
});

What about:

$rows.hover( function(){ $(this).find('.label').toggle(); }, function(){ $(this).find('.label').toggle(); } );

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