jQuery - Using .one() with hover

前端 未结 2 1372
孤街浪徒
孤街浪徒 2021-01-12 04:29

Is there any way to get a hover function to only execute once? This is what I\'m currently trying:

$(\'#ask\').live(\'hover\', function() {

    $(\'#homesea         


        
相关标签:
2条回答
  • 2021-01-12 05:09

    You've already answered yourself, use .one() (not .live()).

    But as lasseespeholt just pointed out in a comment, .hover() is shorthand for binding to mouseenter and mouseleave, and is not an event in itself.

    Try this:

    $('#ask').one('mouseenter', function() {
    
        $('#homesearch-after').hide(300);
    
        $.doTimeout( 300, function() {
            hideClosedSearchLink();
            showHomeSearch();
        });
    
    });
    

    If that still doesn't work, try just using the good ol' .hover() and then .unbind()ing it immediately after it's finished.

    $('#ask').hover(function() {
    
        $('#homesearch-after').hide(300);
    
        $.doTimeout( 300, function() {
            hideClosedSearchLink();
            showHomeSearch();
        });
    
        // Again taking into account what lasseespeholt said
        $(this).unbind('mouseenter mouseleave')
    
    });
    
    0 讨论(0)
  • 2021-01-12 05:09

    hover is not a real event but a shorthand method that binds handlers for two events, mouseenter and mouseleave, and as such doesn't work with .one (as shown here). To replicate the behavior of hover you'd have to have two binds that will both trigger only one time, like this:

    $("#foo").one("mouseenter mouseleave", function(e){
        $(this).toggleClass("bar");
    });
    

    The above would be the same as the following, with the exception that it fires only once:

    $("#foo").hover(function(){
        $(this).toggleClass("bar");
    });
    

    If you want to do different things on mouseenter and mouseleave, you need to bind separate handlers:

    $("#foo").one("mouseenter", function(e){
        $(this).addClass("bar").text("Over");
    }).one("mouseleave", function(e){
        $(this).removeClass("bar").text("Out");
    });
    

    What I can read from your code is that you are only looking to bind the mouseenter event, like this:

    $('#ask').one('mouseenter', function() {
        $('#homesearch-after').hide(300);
        $.doTimeout( 300, function() {
            hideClosedSearchLink();
            showHomeSearch();
        });
    });
    
    0 讨论(0)
提交回复
热议问题